code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
@function inner-border-spread($width) {
$top: top($width);
$right: right($width);
$bottom: bottom($width);
$left: left($width);
@return min(($top + $bottom) / 2, ($left + $right) / 2);
}
@function inner-border-hoff($width, $spread) {
$left: left($width);
$right: right($width);
@if $right <= 0 {
@return $left - $spread;
}
@else {
@return $spread - $right;
}
}
@function inner-border-voff($width, $spread) {
$top: top($width);
$bottom: bottom($width);
@if $bottom <= 0 {
@return $top - $spread;
}
@else {
@return $spread - $bottom;
}
}
@function even($number) {
@return ceil($number / 2) == ($number / 2);
}
@function odd($number) {
@return ceil($number / 2) != ($number / 2);
}
@function inner-border-usesingle-width($width) {
$top: top($width);
$right: right($width);
$bottom: bottom($width);
$left: left($width);
@if $top == 0 {
@if $left + $right == 0 {
@return true;
}
@if $bottom >= $left + $right {
@return true;
}
}
@if $bottom == 0 {
@if $left + $right == 0 {
@return true;
}
@if $top >= $left + $right {
@return true;
}
}
@if $left == 0 {
@if $top + $bottom == 0 {
@return true;
}
@if $right >= $top + $bottom {
@return true;
}
}
@if $right == 0 {
@if $top + $bottom == 0 {
@return true;
}
@if $left >= $top + $bottom {
@return true;
}
}
@if $top + $bottom == $left + $right and even($top) == even($bottom) and even($left) == even($right) {
@return true;
}
@return false;
}
@function inner-border-usesingle-color($color) {
$top: top($color);
$right: right($color);
$bottom: bottom($color);
$left: left($color);
@if $top == $right == $bottom == $left {
@return true;
}
@return false;
}
@function inner-border-usesingle($width, $color) {
@if inner-border-usesingle-color($color) and inner-border-usesingle-width($width) {
@return true;
}
@return false;
}
@mixin inner-border($width: 1px, $color: #fff, $blur: 0px) {
@if inner-border-usesingle($width, $color) {
$spread: inner-border-spread($width);
$hoff: inner-border-hoff($width, $spread);
$voff: inner-border-voff($width, $spread);
@include single-box-shadow($color-top, $hoff, $voff, $blur, $spread, true);
}
@else {
$width-top: top($width);
$width-right: right($width);
$width-bottom: bottom($width);
$width-left: left($width);
$color-top: top($color);
$color-right: right($color);
$color-bottom: bottom($color);
$color-left: left($color);
$shadow-top: false;
$shadow-right: false;
$shadow-bottom: false;
$shadow-left: false;
@if $width-top > 0 {
$shadow-top: $color-top 0 $width-top $blur 0 inset;
}
@if $width-right > 0 {
$shadow-right: $color-right (-1 * $width-right) 0 $blur 0 inset;
}
@if $width-bottom > 0 {
$shadow-bottom: $color-bottom 0 (-1 * $width-bottom) $blur 0 inset;
}
@if $width-left > 0 {
$shadow-left: $color-left $width-left 0 $blur 0 inset;
}
@include box-shadow($shadow-top, $shadow-bottom, $shadow-right, $shadow-left);
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/mixins/_inner-border.scss | SCSS | asf20 | 3,625 |
/**
*
*/
@mixin color-by-background($bg-color, $contrast: 70%, $default-color: null, $bevel-text: true) {
@if ($default-color != null) {
color: $default-color;
} @else {
@if (lightness($bg-color) > 40) {
color: darken($bg-color, $contrast);
}
@else {
color: lighten($bg-color, $contrast)
}
}
@if ($bevel-text != false) {
@if (lightness($bg-color) < 40) {
@include text-shadow(rgba(0,0,0,.5) 0 -1px 0);
} @else {
@include text-shadow(rgba(255,255,255,.25) 0 1px 0);
}
}
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/mixins/_color-by-background.scss | SCSS | asf20 | 606 |
/**
* @mixin background-gradient
*
* @param {Color} $background-color The background color of the gradient
* @param {String/List} $type The type of gradient to be used. Can either be a String which is a predefined gradient, or it can
* can be a list of color_stops. If none is set, it will still set the `background-color` to the $background-color.
* @param {String} $direction The direction of the gradient. Can either me `top` or `left`. (defaults to `top`)
*/
@mixin background-gradient($bg-color, $type: $base-gradient, $direction: top) {
background-image: none;
background-color: $bg-color;
@if $base-gradient != null and $bg-color != transparent {
//color_stops
@if type-of($type) == "list" {
@include background-image(linear-gradient($direction, $type));
}
//default gradients
@else if $type == bevel {
@include background-image(linear-gradient($direction, color_stops(
lighten($bg-color, 15%),
lighten($bg-color, 8%) 30%,
$bg-color 65%,
darken($bg-color, 6%)
)));
} @else if $type == glossy {
@include background-image(linear-gradient($direction, color_stops(lighten($bg-color, 15%), lighten($bg-color, 5%) 50%, $bg-color 51%, darken($bg-color, 5%))));
} @else if $type == recessed {
@include background-image(linear-gradient($direction, color_stops(darken($bg-color, 10%), darken($bg-color, 5%) 10%, $bg-color 65%, lighten($bg-color, .5%))));
} @else if $type == matte {
@include background-image(linear-gradient($direction, color_stops(lighten($bg-color, 3%), darken($bg-color, 4%))));
} @else if $type == matte-reverse {
@include background-image(linear-gradient($direction, color_stops(darken($bg-color, 6%), lighten($bg-color, 4%))));
} @else if $type == glossy-toolbar {
@include background-image(linear-gradient($direction, color_stops(#F0F5FA, #DAE6F4 2%, #CEDDEF)));
}
//ext3.3 gradients
@else if $type == panel-header {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: -0.857deg, $saturation: -1.63%, $lightness: 3.529%),
adjust-color($bg-color, $hue: 0.158deg, $saturation: -1.21%, $lightness: 0.392%) 45%,
adjust-color($bg-color, $hue: 1.154deg, $saturation: 0.607%, $lightness: -7.647%) 46%,
adjust-color($bg-color, $hue: 1.154deg, $saturation: 0.607%, $lightness: -7.647%) 50%,
adjust-color($bg-color, $hue: 1.444deg, $saturation: -1.136%, $lightness: -4.706%) 51%,
$bg-color
)));
} @else if $type == tabbar {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 0.0deg, $saturation: 1.604%, $lightness: 4.706%),
$bg-color
)));
} @else if $type == tab {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 1.382deg, $saturation: -18.571%, $lightness: -4.902%),
adjust-color($bg-color, $hue: 0.43deg, $saturation: -10.311%, $lightness: -2.157%) 25%,
$bg-color 45%
)));
} @else if $type == tab-active {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: -212.903deg, $saturation: -88.571%, $lightness: 6.863%),
adjust-color($bg-color, $hue: 0.43deg, $saturation: -6.753%, $lightness: 4.706%) 25%,
$bg-color 45%
)));
} @else if $type == tab-over {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 4.462deg, $saturation: -9.524%, $lightness: -3.725%),
adjust-color($bg-color, $hue: 2.272deg, $saturation: 0.0%, $lightness: -1.569%) 25%,
$bg-color 45%
)));
} @else if $type == tab-disabled {
@include background-image(linear-gradient($direction, color_stops(
$bg-color,
adjust-color($bg-color, $hue: -0.267deg, $saturation: 18.571%, $lightness: 2.941%)
)));
} @else if $type == grid-header {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 0deg, $saturation: 0%, $lightness: 20.392%),
adjust-color($bg-color, $hue: 220.0deg, $saturation: 5.66%, $lightness: 12.353%)
)));
} @else if $type == grid-header-over {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 0.175deg, $saturation: 0.967%, $lightness: 14.118%),
adjust-color($bg-color, $hue: 0.175deg, $saturation: 0.967%, $lightness: 14.118%) 39%,
adjust-color($bg-color, $hue: 0.372deg, $saturation: 0.101%, $lightness: 10.196%) 40%,
adjust-color($bg-color, $hue: 0.372deg, $saturation: 0.101%, $lightness: 10.196%)
)));
} @else if $type == grid-row-over {
@include background-image(linear-gradient($direction, color_stops(
adjust-color($bg-color, $hue: 0.175deg, $saturation: 0.967%, $lightness: 14.118%),
$bg-color
)));
} @else if $type == grid-cell-special {
@include background-image(linear-gradient(left, color_stops(
$bg-color,
darken($bg-color, 5)
)));
} @else if $type == glossy-button or $type == glossy-button-disabled {
@include background-image(linear-gradient($direction, color_stops(
$bg-color,
adjust-color($bg-color, $hue: 0deg, $saturation: 0%, $lightness: -2.353%) 48%,
adjust-color($bg-color, $hue: 0deg, $saturation: 0%, $lightness: -11.373%) 52%,
adjust-color($bg-color, $hue: 0deg, $saturation: 0%, $lightness: -9.412%)
)));
} @else if $type == glossy-button-over {
@include background-image(linear-gradient($direction, color_stops(
$bg-color,
adjust-color($bg-color, $hue: 1.754deg, $saturation: 0.0%, $lightness: -2.157%) 48%,
adjust-color($bg-color, $hue: 5.833deg, $saturation: -35.135%, $lightness: -9.216%) 52%,
adjust-color($bg-color, $hue: 5.833deg, $saturation: -27.273%, $lightness: -7.647%)
)));
} @else if $type == glossy-button-pressed {
@include background-image(linear-gradient($direction, color_stops(
$bg-color,
adjust-color($bg-color, $hue: -1.839deg, $saturation: -2.18%, $lightness: 2.157%) 48%,
adjust-color($bg-color, $hue: -2.032deg, $saturation: 37.871%, $lightness: -4.706%) 52%,
adjust-color($bg-color, $hue: -1.641deg, $saturation: 36.301%, $lightness: -2.549%)
)));
}
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/mixins/_background-gradient.scss | SCSS | asf20 | 7,233 |
@mixin x-frame(
$cls,
$ui: null,
$border-radius: 0px,
$border-width: 0px,
$padding: null,
$background-color: null,
$background-gradient: null,
$table: false,
$background-direction: top
) {
$cls-ui: $cls;
@if $ui != null {
$cls-ui: $cls + '-' + $ui;
}
$vertical: false;
@if $background-direction == left or $background-direction == right {
$vertical: true;
}
$frame-top: max(top($border-radius), right($border-radius));
$frame-right: max(right($border-radius), bottom($border-radius));
$frame-bottom: max(bottom($border-radius), left($border-radius));
$frame-left: max(left($border-radius), top($border-radius));
$padding-top: 0;
$padding-right: 0;
$padding-bottom: 0;
$padding-left: 0;
@if $padding == null {
$padding-top: $frame-top - top($border-width);
$padding-right: $frame-right - right($border-width);
$padding-bottom: $frame-bottom - bottom($border-width);
$padding-left: $frame-left - left($border-width);
}
@else {
$padding-top: top($padding);
$padding-right: right($padding);
$padding-bottom: bottom($padding);
$padding-left: left($padding);
}
@if $padding-top < $frame-top {
$padding-top: $frame-top - top($border-width);
}
@if $padding-right < $frame-right {
$padding-right: $frame-right - right($border-width);
}
@if $padding-bottom < $frame-bottom {
$padding-bottom: $frame-bottom - bottom($border-width);
}
@if $padding-left < $frame-left {
$padding-left: $frame-left - left($border-width);
}
.#{$prefix}#{$cls-ui} {
@if $supports-border-radius {
@if length($border-radius) == 2 {
@include border-top-left-radius(nth($border-radius, 1));
@include border-top-right-radius(nth($border-radius, 2));
} @else if length($border-radius) == 3 {
@include border-top-left-radius(nth($border-radius, 1));
@include border-top-right-radius(nth($border-radius, 2));
@include border-bottom-right-radius(nth($border-radius, 3));
} @else if length($border-radius) == 4 {
@include border-top-left-radius(nth($border-radius, 1));
@include border-top-right-radius(nth($border-radius, 2));
@include border-bottom-right-radius(nth($border-radius, 3));
@include border-bottom-left-radius(nth($border-radius, 4));
} @else {
@include border-radius($border-radius);
}
}
padding: $padding-top $padding-right $padding-bottom $padding-left;
border-width: $border-width;
border-style: solid;
@if $background-color != null {
@if $supports-gradients and $background-gradient != null {
@include background-gradient($background-color, $background-gradient, $background-direction);
}
@else {
background-color: $background-color;
}
}
}
@if not $supports-gradients or $compile-all {
.#{$prefix}nlg {
.#{$prefix}#{$cls-ui}-mc {
@if $background-gradient != null {
background-image: theme-background-image($theme-name, '#{$cls}/#{$cls-ui}-bg.gif', false, $relative-image-path-for-uis);
}
@if $background-color != null {
background-color: $background-color;
}
}
}
}
@if not $supports-border-radius or $compile-all {
.#{$prefix}nbr {
.#{$prefix}#{$cls-ui} {
padding: 0 !important;
border-width: 0 !important;
@include border-radius(0px);
@if $background-color != null {
background-color: transparent;
}
@else {
background: #fff;
}
@function pad($radius) {
$radius: boxmax($radius);
$radius: parseint($radius);
@if $radius > 10 {
@return $radius;
}
@else {
@return "0" + $radius;
}
}
$type: '100';
@if $table == true {
$type: '110';
}
$direction: '100';
@if $vertical == true {
$direction: '110';
}
$left: $type + pad(top($border-radius)) + pad(right($border-radius)) + 'px';
$top: $direction + pad(bottom($border-radius)) + pad(left($border-radius)) + 'px';
background-position: unquote($left) unquote($top);
}
.#{$prefix}#{$cls-ui}-tl,
.#{$prefix}#{$cls-ui}-bl,
.#{$prefix}#{$cls-ui}-tr,
.#{$prefix}#{$cls-ui}-br,
.#{$prefix}#{$cls-ui}-tc,
.#{$prefix}#{$cls-ui}-bc,
.#{$prefix}#{$cls-ui}-ml,
.#{$prefix}#{$cls-ui}-mr {
zoom:1;
@if $background-color != transparent {
background-image: theme-background-image($theme-name, '#{$cls}/#{$cls-ui}-corners.gif', false, $relative-image-path-for-uis);
}
}
@if $vertical == true {
.#{$prefix}#{$cls-ui}-tc,
.#{$prefix}#{$cls-ui}-bc {
zoom:1;
@if $background-color != transparent {
background-image: theme-background-image($theme-name, '#{$cls}/#{$cls-ui}-sides.gif', false, $relative-image-path-for-uis);
background-position: 0 0;
background-repeat: repeat-x;
}
}
} @else {
.#{$prefix}#{$cls-ui}-ml,
.#{$prefix}#{$cls-ui}-mr {
zoom:1;
@if $background-color != transparent {
background-image: theme-background-image($theme-name, '#{$cls}/#{$cls-ui}-sides.gif', false, $relative-image-path-for-uis);
background-position: 0 0;
@if $background-gradient == null {
background-repeat: repeat-y;
}
}
}
}
$padding-top: $padding-top - $frame-top;
$padding-right: $padding-right - $frame-right;
$padding-bottom: $padding-bottom - $frame-bottom;
$padding-left: $padding-left - $frame-left;
@if $padding-top < 0 {
$padding-top: 0;
}
@if $padding-right < 0 {
$padding-right: 0;
}
@if $padding-bottom < 0 {
$padding-bottom: 0;
}
@if $padding-left < 0 {
$padding-left: 0;
}
.#{$prefix}#{$cls-ui}-mc {
padding: $padding-top $padding-right $padding-bottom $padding-left;
}
}
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/mixins/_frame.scss | SCSS | asf20 | 7,462 |
@import "compass/css3";
@import "blueprint/typography";
$include-default: true !default;
$include-default-uis: true !default;
@import 'functions';
@import 'variables';
@import 'mixins';
//core
@import 'core';
//layout
@import 'layout/layout';
//utils
@import 'util/tool';
@import 'util/messagebox';
@import 'util/splitter';
@import 'util/resizable';
@import 'util/dragdrop';
@import 'util/scroller';
@import 'util/focus';
//widgets
@import 'widgets';
@if $scope-reset-css {
.#{$prefix}reset {
@if $include-default {
@include extjs-boundlist;
@include extjs-button;
@include extjs-btn-group;
@include extjs-datepicker;
@include extjs-colorpicker;
@include extjs-menu;
@include extjs-grid;
@include extjs-form;
@include extjs-form-field;
@include extjs-form-fieldset;
@include extjs-form-file;
@include extjs-form-checkboxfield;
@include extjs-form-checkboxgroup;
@include extjs-form-triggerfield;
@include extjs-form-htmleditor;
@include extjs-panel;
@include extjs-qtip;
@include extjs-slider;
@include extjs-progress;
@include extjs-toolbar;
@include extjs-window;
@include extjs-messagebox;
@include extjs-tabbar;
@include extjs-tab;
@include extjs-tree;
@include extjs-drawcomponent;
@include extjs-viewport;
}
@include extjs-dragdrop;
@include extjs-resizable;
@include extjs-splitter;
@include extjs-layout;
@include extjs-tool;
@include extjs-scroller;
@include extjs-html;
}
@include extjs-reset-extras;
}
@else {
@if $include-default {
@include extjs-boundlist;
@include extjs-button;
@include extjs-btn-group;
@include extjs-datepicker;
@include extjs-colorpicker;
@include extjs-menu;
@include extjs-grid;
@include extjs-form;
@include extjs-form-field;
@include extjs-form-fieldset;
@include extjs-form-file;
@include extjs-form-checkboxfield;
@include extjs-form-checkboxgroup;
@include extjs-form-triggerfield;
@include extjs-form-htmleditor;
@include extjs-panel;
@include extjs-qtip;
@include extjs-slider;
@include extjs-progress;
@include extjs-toolbar;
@include extjs-window;
@include extjs-messagebox;
@include extjs-tabbar;
@include extjs-tab;
@include extjs-tree;
@include extjs-drawcomponent;
@include extjs-viewport;
}
@include extjs-dragdrop;
@include extjs-resizable;
@include extjs-splitter;
@include extjs-layout;
@include extjs-tool;
@include extjs-scroller;
@include extjs-html;
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/_all.scss | SCSS | asf20 | 2,907 |
@import 'variables/core';
$mix-color: desaturate(lighten($base-color, 37), 5) !default;
@import 'variables/focus';
@import 'variables/panel';
@import 'variables/grid';
@import 'variables/button';
@import 'variables/pickers';
@import 'variables/toolbar';
@import 'variables/form';
@import 'variables/menu';
@import 'variables/window';
@import 'variables/tabs';
@import 'variables/qtip';
@import 'variables/progress-bar';
@import 'variables/btn-group';
@import 'variables/boundlist';
@import 'variables/tree';
@import 'variables/layout';
@import 'variables/loadmask';
@import 'variables/htmleditor';
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/_variables.scss | SCSS | asf20 | 619 |
@mixin extjs-scroller {
.#{$prefix}horizontal-scroller-present .#{$prefix}grid-body {
border-bottom-width: 0px;
}
.#{$prefix}vertical-scroller-present .#{$prefix}grid-body {
border-right-width: 0px;
}
.#{$prefix}scroller {
overflow: hidden;
}
.#{$prefix}scroller-vertical {
border: 1px solid $panel-border-color;
border-top-color: $grid-header-background-color;
}
.#{$prefix}scroller-horizontal {
border: 1px solid $panel-border-color;
}
.#{$prefix}vertical-scroller-present .#{$prefix}scroller-horizontal {
border-right-width: 0px;
}
.#{$prefix}scroller-ct {
overflow: hidden;
position: absolute;
margin: 0;
padding: 0;
border: none;
left: 0px;
top: 0px;
/*
In IE9 (only), the border-box style causes the scroller-ct to be 0px in the
perpendicular dimension and breaks the scroll as well as offsets it by the left
offset that we use to try and keep some size on this element. This works on all
browsers (including IE9).
*/
box-sizing: content-box !important;
-ms-box-sizing: content-box !important;
-moz-box-sizing: content-box !important;
-webkit-box-sizing: content-box !important;
}
.#{$prefix}scroller-vertical .#{$prefix}scroller-ct {
overflow-y: scroll;
}
.#{$prefix}scroller-horizontal .#{$prefix}scroller-ct {
overflow-x: scroll;
}
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_scroller.scss | SCSS | asf20 | 1,560 |
@mixin extjs-splitter {
.#{$prefix}splitter {
.#{$prefix}collapse-el {
position: absolute;
cursor: pointer;
background-color: transparent;
background-repeat: no-repeat !important;
}
}
.#{$prefix}layout-split-left,
.#{$prefix}layout-split-right {
top: 50%;
margin-top: -17px;
width: 5px;
height: 35px;
}
.#{$prefix}layout-split-top,
.#{$prefix}layout-split-bottom {
left: 50%;
width: 35px;
height: 5px;
margin-left: -17px;
}
.#{$prefix}layout-split-left {
background: no-repeat top right;
background-image: theme-background-image($theme-name, 'util/splitter/mini-left.gif');
}
.#{$prefix}layout-split-right {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-right.gif');
}
.#{$prefix}layout-split-top {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-top.gif');
}
.#{$prefix}layout-split-bottom {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-bottom.gif');
}
.#{$prefix}splitter-collapsed {
.#{$prefix}layout-split-left {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-right.gif');
}
.#{$prefix}layout-split-right {
background: no-repeat top right;
background-image: theme-background-image($theme-name, 'util/splitter/mini-left.gif');
}
.#{$prefix}layout-split-top {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-bottom.gif');
}
.#{$prefix}layout-split-bottom {
background: no-repeat top left;
background-image: theme-background-image($theme-name, 'util/splitter/mini-top.gif');
}
}
.#{$prefix}splitter-horizontal {
cursor: e-resize;
cursor: row-resize;
font-size:1px;
}
.#{$prefix}splitter-vertical {
cursor: e-resize;
cursor: col-resize;
font-size:1px;
}
.#{$prefix}splitter-collapsed {
cursor: default;
}
.#{$prefix}splitter-active {
z-index: 4;
font-size:1px;
background-color: rgb(180, 180, 180);
@include opacity(0.8);
}
.#{$prefix}splitter-active {
.#{$prefix}collapse-el {
@include opacity(0.3);
}
}
.#{$prefix}proxy-el {
position: absolute;
background: rgb(180, 180, 180);
@include opacity(0.8);
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_splitter.scss | SCSS | asf20 | 2,832 |
@mixin extjs-dragdrop {
.#{$prefix}dd-drag-proxy {
}
.#{$prefix}dd-drag-repair {
.#{$prefix}dd-drag-ghost {
@include opacity(.6);
}
.#{$prefix}dd-drop-icon {
display: none;
}
}
.#{$prefix}dd-drag-ghost {
@include opacity(.85);
padding: 5px;
padding-left: 20px;
white-space: nowrap;
color: #000;
font: normal ceil($font-size * .9) $font-family;
border: 1px solid;
border-color: #ddd #bbb #bbb #ddd;
background-color: #fff;
}
.#{$prefix}dd-drop-icon {
position: absolute;
top: 3px;
left: 3px;
display: block;
width: 16px;
height: 16px;
background-color: transparent;
background-position: center;
background-repeat: no-repeat;
z-index: 1;
}
.#{$prefix}view-selector {
position: absolute;
left: 0;
top: 0;
width: 0;
background-color: #c3daf9;
border: 1px dotted #3399bb;
@include opacity(.5);
zoom: 1;
}
.#{$prefix}dd-drop-nodrop .#{$prefix}dd-drop-icon {
background-image: theme-background-image($theme-name, 'dd/drop-no.gif');
}
.#{$prefix}dd-drop-ok .#{$prefix}dd-drop-icon {
background-image: theme-background-image($theme-name, 'dd/drop-yes.gif');
}
.#{$prefix}dd-drop-ok-add .#{$prefix}dd-drop-icon {
background-image: theme-background-image($theme-name, 'dd/drop-add.gif');
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_dragdrop.scss | SCSS | asf20 | 1,688 |
@mixin extjs-messagebox {
.#{$prefix}message-box .#{$prefix}window-body {
background-color: $window-background-color;
border: none;
}
.#{$prefix}message-box .ext-mb-textarea {
margin-top: 4px;
}
.#{$prefix}message-box .#{$prefix}progress-wrap {
margin-top: 4px;
}
.#{$prefix}message-box .ext-mb-icon {
width: 47px;
height: 32px;
}
.#{$prefix}message-box .ext-mb-info,
.#{$prefix}message-box .ext-mb-warning,
.#{$prefix}message-box .ext-mb-question,
.#{$prefix}message-box .ext-mb-error {
background: transparent no-repeat top left;
}
.ext-gecko2 .ext-mb-fix-cursor {
overflow: auto;
}
.#{$prefix}message-box .#{$prefix}msg-box-wait {
background-image: theme-background-image($theme-name, 'shared/blue-loading.gif');
}
.#{$prefix}message-box .ext-mb-info {
background-image: theme-background-image($theme-name, 'shared/icon-info.gif');
}
.#{$prefix}message-box .ext-mb-warning {
background-image: theme-background-image($theme-name, 'shared/icon-warning.gif');
}
.#{$prefix}message-box .ext-mb-question {
background-image: theme-background-image($theme-name, 'shared/icon-question.gif');
}
.#{$prefix}message-box .ext-mb-error {
background-image: theme-background-image($theme-name, 'shared/icon-error.gif');
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_messagebox.scss | SCSS | asf20 | 1,425 |
@mixin extjs-resizable {
.#{$prefix}resizable-handle {
position: absolute;
z-index: 100;
font-size: 1px;
line-height: 6px;
overflow: hidden;
zoom: 1;
@include opacity(0);
background-color: #fff;
}
.#{$prefix}resizable-handle-east {
width: 6px;
height: 100%;
right: 0;
top: 0;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-east {
cursor: e-resize;
}
}
.#{$prefix}resizable-handle-south {
width: 100%;
height: 6px;
left: 0;
bottom: 0;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-south {
cursor: s-resize;
}
}
.#{$prefix}resizable-handle-west {
width: 6px;
height: 100%;
left: 0;
top: 0;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-west {
cursor: w-resize;
}
}
.#{$prefix}resizable-handle-north {
width: 100%;
height: 6px;
left: 0;
top: 0;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-north {
cursor: n-resize;
}
}
.#{$prefix}resizable-handle-southeast {
width: 6px;
height: 6px;
right: 0;
bottom: 0;
z-index: 101;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-southeast {
cursor: se-resize;
}
}
.#{$prefix}resizable-handle-northwest {
width: 6px;
height: 6px;
left: 0;
top: 0;
z-index: 101;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-northwest {
cursor: nw-resize;
}
}
.#{$prefix}resizable-handle-northeast {
width: 6px;
height: 6px;
right: 0;
top: 0;
z-index: 101;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-northeast {
cursor: ne-resize;
}
}
.#{$prefix}resizable-handle-southwest {
width: 6px;
height: 6px;
left: 0;
bottom: 0;
z-index: 101;
}
.#{$prefix}resizable-over {
.#{$prefix}resizable-handle-southwest {
cursor: sw-resize;
}
}
/*IE rounding error*/
.#{$prefix}ie {
.#{$prefix}resizable-handle-east {
margin-right: -1px; /*IE rounding error*/
}
.#{$prefix}resizable-handle-south {
margin-bottom: -1px;
}
}
.#{$prefix}resizable-over .#{$prefix}resizable-handle, .#{$prefix}resizable-pinned .#{$prefix}resizable-handle{
@include opacity(1);
}
.#{$prefix}window .#{$prefix}window-handle {
@include opacity(0);
}
.#{$prefix}window-collapsed .#{$prefix}window-handle {
display: none;
}
.#{$prefix}resizable-proxy {
border: 1px dashed #3b5a82;
position: absolute;
left: 0;
top: 0;
overflow: hidden;
z-index: 50000;
}
.#{$prefix}resizable-overlay {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: none;
z-index: 200000;
background-color: #fff;
@include opacity(0);
}
.#{$prefix}resizable-over,
.#{$prefix}resizable-pinned {
.#{$prefix}resizable-handle-east,
.#{$prefix}resizable-handle-west {
background-position: left;
background-image: theme-background-image($theme-name, 'sizer/e-handle.gif');
}
.#{$prefix}resizable-handle-south,
.#{$prefix}resizable-handle-north {
background-position: top;
background-image: theme-background-image($theme-name, 'sizer/s-handle.gif');
}
.#{$prefix}resizable-handle-southeast {
background-position: top left;
background-image: theme-background-image($theme-name, 'sizer/se-handle.gif');
}
.#{$prefix}resizable-handle-northwest {
background-position: bottom right;
background-image: theme-background-image($theme-name, 'sizer/nw-handle.gif');
}
.#{$prefix}resizable-handle-northeast {
background-position: bottom left;
background-image: theme-background-image($theme-name, 'sizer/ne-handle.gif');
}
.#{$prefix}resizable-handle-southwest {
background-position: top right;
background-image: theme-background-image($theme-name, 'sizer/sw-handle.gif');
}
}
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_resizable.scss | SCSS | asf20 | 4,981 |
.#{$prefix}focus-element {
position: absolute;
top: -10px;
left: -10px;
width: 0px;
height: 0px;
}
.#{$prefix}focus-frame {
position: absolute;
left: 0px;
top: 0px;
z-index: 100000000;
width: 0px;
height: 0px;
}
.#{$prefix}focus-frame-top,
.#{$prefix}focus-frame-bottom,
.#{$prefix}focus-frame-left,
.#{$prefix}focus-frame-right {
position: absolute;
top: 0px;
left: 0px;
}
.#{$prefix}focus-frame-top,
.#{$prefix}focus-frame-bottom {
border-top: $focus-frame-style $focus-frame-width $focus-frame-color;
height: $focus-frame-width;
}
.#{$prefix}focus-frame-left,
.#{$prefix}focus-frame-right {
border-left: $focus-frame-style $focus-frame-width $focus-frame-color;
width: $focus-frame-width;
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_focus.scss | SCSS | asf20 | 770 |
@mixin extjs-tool {
.#{$prefix}tool {
height: $tool-size;
img {
overflow: hidden;
width: $tool-size;
height: $tool-size;
cursor: pointer;
background-color: transparent;
background-repeat: no-repeat;
background-image: theme-background-image($theme-name, 'tools/tool-sprites.gif');
margin: 0;
}
}
.#{$prefix}panel-header-horizontal,
.#{$prefix}window-header-horizontal {
.#{$prefix}tool {
margin-left: 2px;
}
}
.#{$prefix}panel-header-vertical,
.#{$prefix}window-header-vertical {
.#{$prefix}tool {
margin-bottom: 2px;
}
}
.#{$prefix}tool-placeholder {
visibility: hidden;
}
.#{$prefix}tool-toggle {
background-position: 0 -60px;
}
.#{$prefix}tool-over {
.#{$prefix}tool-toggle {
background-position: -15px -60px;
}
}
.#{$prefix}panel-collapsed,
.#{$prefix}fieldset-collapsed {
.#{$prefix}tool-toggle {
background-position: 0 -75px;
}
.#{$prefix}tool-over {
.#{$prefix}tool-toggle {
background-position: -15px -75px;
}
}
}
.#{$prefix}tool-close {
background-position: 0 0;
}
.#{$prefix}tool-minimize {
background-position: 0 -15px;
}
.#{$prefix}tool-maximize {
background-position: 0 -30px;
}
.#{$prefix}tool-restore {
background-position: 0 -45px;
}
.#{$prefix}tool-gear {
background-position: 0 -90px;
}
.#{$prefix}tool-prev {
background-position: 0 -105px;
}
.#{$prefix}tool-next {
background-position: 0 -120px;
}
.#{$prefix}tool-pin {
background-position: 0 -135px;
}
.#{$prefix}tool-unpin {
background-position: 0 -150px;
}
.#{$prefix}tool-right {
background-position: 0 -165px;
}
.#{$prefix}tool-left {
background-position: 0 -180px;
}
.#{$prefix}tool-help {
background-position: 0 -300px;
}
.#{$prefix}tool-save {
background-position: 0 -285px;
}
.#{$prefix}tool-search {
background-position: 0 -270px;
}
.#{$prefix}tool-minus {
background-position: 0 -255px;
}
.#{$prefix}tool-plus {
background-position: 0 -240px;
}
.#{$prefix}tool-refresh {
background-position: 0 -225px;
}
.#{$prefix}tool-up {
background-position: 0 -210px;
}
.#{$prefix}tool-down {
background-position: 0 -195px;
}
.#{$prefix}tool-move {
background-position: 0 -375px;
}
.#{$prefix}tool-resize {
background-position: 0 -360px;
}
.#{$prefix}tool-collapse {
background-position: 0 -345px;
}
.#{$prefix}tool-expand {
background-position: 0 -330px;
}
.#{$prefix}tool-print {
background-position: 0 -315px;
}
.#{$prefix}tool-expand-bottom,
.#{$prefix}tool-collapse-bottom {
background-position: 0 -195px;
}
.#{$prefix}tool-expand-top,
.#{$prefix}tool-collapse-top {
background-position: 0 -210px;
}
.#{$prefix}tool-expand-left,
.#{$prefix}tool-collapse-left {
background-position: 0 -180px;
}
.#{$prefix}tool-expand-right,
.#{$prefix}tool-collapse-right {
background-position: 0 -165px;
}
.#{$prefix}tool-over {
.#{$prefix}tool-close {
background-position: -15px 0;
}
.#{$prefix}tool-minimize {
background-position: -15px -15px;
}
.#{$prefix}tool-maximize {
background-position: -15px -30px;
}
.#{$prefix}tool-restore {
background-position: -15px -45px;
}
.#{$prefix}tool-gear {
background-position: -15px -90px;
}
.#{$prefix}tool-prev {
background-position: -15px -105px;
}
.#{$prefix}tool-next {
background-position: -15px -120px;
}
.#{$prefix}tool-pin {
background-position: -15px -135px;
}
.#{$prefix}tool-unpin {
background-position: -15px -150px;
}
.#{$prefix}tool-right {
background-position: -15px -165px;
}
.#{$prefix}tool-left {
background-position: -15px -180px;
}
.#{$prefix}tool-down {
background-position: -15px -195px;
}
.#{$prefix}tool-up {
background-position: -15px -210px;
}
.#{$prefix}tool-refresh {
background-position: -15px -225px;
}
.#{$prefix}tool-plus {
background-position: -15px -240px;
}
.#{$prefix}tool-minus {
background-position: -15px -255px;
}
.#{$prefix}tool-search {
background-position: -15px -270px;
}
.#{$prefix}tool-save {
background-position: -15px -285px;
}
.#{$prefix}tool-help {
background-position: -15px -300px;
}
.#{$prefix}tool-print {
background-position: -15px -315px;
}
.#{$prefix}tool-expand {
background-position: -15px -330px;
}
.#{$prefix}tool-collapse {
background-position: -15px -345px;
}
.#{$prefix}tool-resize {
background-position: -15px -360px;
}
.#{$prefix}tool-move {
background-position: -15px -375px;
}
.#{$prefix}tool-expand-bottom,
.#{$prefix}tool-collapse-bottom {
background-position: -15px -195px;
}
.#{$prefix}tool-expand-top,
.#{$prefix}tool-collapse-top {
background-position: -15px -210px;
}
.#{$prefix}tool-expand-left,
.#{$prefix}tool-collapse-left {
background-position: -15px -180px;
}
.#{$prefix}tool-expand-right,
.#{$prefix}tool-collapse-right {
background-position: -15px -165px;
}
}
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/stylesheets/ext4/default/util/_tool.scss | SCSS | asf20 | 6,386 |
module ExtJS4
module SassExtensions
module Functions
module Utils
def parsebox(list, n)
assert_type n, :Number
if !n.int?
raise ArgumentError.new("List index #{n} must be an integer")
elsif n.to_i < 1
raise ArgumentError.new("List index #{n} must be greater than or equal to 1")
elsif n.to_i > 4
raise ArgumentError.new("A box string can't contain more then 4")
end
new_list = list.clone.to_a
size = new_list.size
if n.to_i >= size
if size == 1
new_list[1] = new_list[0]
new_list[2] = new_list[0]
new_list[3] = new_list[0]
elsif size == 2
new_list[2] = new_list[0]
new_list[3] = new_list[1]
elsif size == 3
new_list[3] = new_list[1]
end
end
new_list.to_a[n.to_i - 1]
end
def parseint(value)
Sass::Script::Number.new(value.to_i)
end
# Returns a background-image property for a specified images for the theme
def theme_image(theme, path, without_url = false, relative = false)
path = path.value
theme = theme.value
without_url = (without_url.class == FalseClass) ? without_url : without_url.value
relative_path = "../images/"
if relative
if relative.class == Sass::Script::String
relative_path = relative.value
relative = true
elsif relative.class == FalseClass || relative.class == TrueClass
relative = relative
else
relative = relative.value
end
else
relative = false
end
if relative
image_path = File.join(relative_path, theme, path)
else
images_path = File.join($ext_path, 'resources', 'themes', 'images', theme)
image_path = File.join(images_path, path)
end
if !without_url
url = "url('#{image_path}')"
else
url = "#{image_path}"
end
Sass::Script::String.new(url)
end
def theme_image_exists(path)
result = false
where_to_look = path.value.gsub('../../resources', 'resources')
if where_to_look && FileTest.exists?("#{where_to_look}")
result = true
end
return Sass::Script::Bool.new(result)
end
end
end
end
end
module Sass::Script::Functions
include ExtJS4::SassExtensions::Functions::Utils
end | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/themes/lib/utils.rb | Ruby | asf20 | 2,762 |
.readOnlyFiled
{
border: 3px;
border-color: Red;
}
#title-logo .x-plain-body
{
background: #f0edce url('../titleLogo.jpg') no-repeat;
}
.application_side_tree
{
background-image: url(/Content/16Icons/application_side_tree.png) !important;
}
.textfield_rename
{
background-image: url(/Content/16Icons/textfield_rename.png) !important;
}
.textfield
{
background-image: url(/Content/16Icons/textfield.png) !important;
}
.new
{
background-image: url(/Content/16Icons/new.png) !important;
}
.accept
{
background-image: url(/Content/16Icons/accept.png) !important;
}
.eye
{
background-image: url(/Content/16Icons/eye.png) !important;
}
.plugin
{
background-image: url(/Content/16Icons/plugin.png) !important;
}
.database_gear
{
background-image: url(/Content/16Icons/database_gear.png) !important;
}
.database_lightning
{
background-image: url(/Content/16Icons/database_lightning.png) !important;
}
.house
{
background-image: url(/Content/16Icons/house.png) !important;
}
.application_side_tree
{
background-image: url(/Content/16Icons/application_side_tree.png) !important;
}
.asterisk_orange
{
background-image: url(/Content/16Icons/asterisk_orange.png) !important;
}
.application_form
{
background-image: url(/Content/16Icons/application_form.png) !important;
}
.new-view-refresh
{
background-image: url(/Content/24Icons/new-view-refresh.png) !important;
}
.kcoloredit
{
background-image: url(/Content/24Icons/kcoloredit.png) !important;
}
.zoom
{
background-image: url(/Content/16Icons/zoom.png) !important;
}
.folder_add16
{
background-image: url(/Content/16Icons/folder_add.png) !important;
}
.group_add1
{
background: url(/Content/GroupImages.png) no-repeat 0px 0px;
width: 13px;
}
.group_add2
{
background: url(/Content/GroupImages.png) no-repeat -13px 0px;
width: 13px;
}
.group_add3
{
background: url(/Content/GroupImages.png) no-repeat -52px 0px;
width: 13px;
}
.group_add4
{
background: url(/Content/GroupImages.png) no-repeat -65px 0px;
width: 13px;
}
.group_add5
{
background: url(/Content/GroupImages.png) no-repeat -91px 0px;
width: 13px;
}
.resultset_next
{
background-image: url(/Content/16Icons/disconnect.png) !important;
}
.ItemSum
{
background-image: url(/Content/16Icons/ItemSum.png) !important;
}
.ItemMax
{
background-image: url(/Content/16Icons/ItemMax.png) !important;
}
.exclamation
{
background-image: url(/Content/16Icons/exclamation.png) !important;
}
.arrow_refresh
{
background-image: url(/Content/16Icons/arrow_refresh.png) !important;
}
| zz-ms | trunk/zz-ms-v1.0/WebContent/resources/css/iconCss.css | CSS | asf20 | 2,787 |
.x-btn-inner {
font-size : 12px;
}
.x-grid-cell-inner {
font-size : 12px;
}
.desk {
background-image: url('../images/pages/user.png');
}
.icon-add {
background-image: url(../images/icons/fam/add.png) !important;
}
.icon-delete {
background-image: url(../images/icons/fam/delete.png) !important;
}
.x-ie6 .icon-user {
background-image: url(../images/icons/fam/user.gif) !important;
}
.x-ie6 .icon-add {
background-image: url(../images/icons/fam/add.gif) !important;
}
.x-ie6 .icon-delete {
background-image: url(../images/icons/fam/delete.gif) !important;
}
.icon-refresh{background-image: url(../images/icons/fam/refresh.gif) !important;} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/css/jzz.css | CSS | asf20 | 676 |
body {
margin: 0 ;
padding: 0;
background-color:#EEF2F6;
}
.login-icon{
background: url(../images/login/login.png) no-repeat !important;
}
.btn-login{
background: url(../images/login/blogin.png) no-repeat !important;
}
.btn-login-reset{
background: url(../images/login/login-reset.png) no-repeat !important;
}
.company {
background: url('../images/login/code.gif') no-repeat 80px 2px;
}
.username {
background: url('../images/login/user.png') no-repeat 80px 2px;
}
.password {
background: url('../images/login/bind.png') no-repeat 80px 2px;
}
.appstyle {
background: url('../images/login/dynamic.png') no-repeat 80px 2px;
}
.verifycode {
background: url('../images/login/lock.gif') no-repeat 80px 2px;
}
.company,.username,.password,.appstyle,.verifycode {
background-color: #FFFFFF;
font-size: 12px;
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/css/appLogin.css | CSS | asf20 | 847 |
/* 解决IE下PNG图片透明Bug */
.IEPNG {
behavior: url(../images/pages/iepngfix.htc);
}
.banner {
font-family: "宋体";
font-size: 12px;
color:4798D7;
}
p {
margin: 5px;
}
.x-panel-header-text-default {
font-size: 12px;
}
.x-tab-inner {
font-size: 12px;
}
.settings {
background-image: url('../images/icons/fam/folder_wrench.png');
}
.nav {
background-image: url('../images/icons/fam/folder_go.png');
}
.info {
background-image: url('../images/icons/fam/information.png');
}
.config24Icon {
background-image:url('../images/icons/24Icons/config.png') !important;
}
.exit24Icon {
background-image:url('../images/icons/24Icons/logoff.png') !important;
}
.switch24Icon {
background-image:url('../images/icons/24Icons/kcoloredit.png') !important;
} | zz-ms | trunk/zz-ms-v1.0/WebContent/resources/css/appIndex.css | CSS | asf20 | 844 |
Ext.Loader.setConfig({
enabled: true
});
var JzzApp = null;
Ext.application({
name: 'Jzz',
appFolder: 'app/mvc',
controllers: ['Main', 'User'],
launch: function() {
//Ext.require('Jzz.view.main.Footer');
JzzApp = this;
Ext.QuickTips.init();
Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
var viewport = Ext.create('Ext.Viewport', {
id: 'main-app',
layout: 'border',
items: [
{
xtype: 'mainHeader'
},
//{
// xtype: 'mainFooter'
//},
//{
// xtype: 'mainOnline'
//},
{
xtype: 'mainMenu'
},
{
xtype: 'mainContent'
}
]
});
//初始化头部按钮
var mainMenu = Ext.create('Ext.menu.Menu', {
id : 'mainMenu',
items : [{
text : '密码修改',
iconCls : 'keyIcon',
handler : function() {
//updateUserInit();
ShowInfoMsg('info', 'change password');
}
}, {
text : '系统锁定',
iconCls : 'lockIcon',
handler : function() {
//lockWindow.show();
//setCookie("g4.lockflag", '1', 240);
ShowInfoMsg('info', 'lock system');
}
}]
});
//创建按钮
Ext.create('Ext.Button', {
text : '切换模块',
iconCls : 'switch24Icon',
iconAlign : 'left',
scale : 'medium',
width : 100,
tooltip : '切换模块',
pressed : true,
renderTo : 'switchModuleDiv',
menu : mainMenu
});
Ext.create('Ext.Button', {
id: 'btn_login_skin',
text : '皮肤',
iconAlign : 'left',
icon : 'resources/images/icons/16Icons/163.png',
scale : 'medium',
width : 60,
tooltip : '更换皮肤',
pressed : true,
renderTo : 'themeDiv',
enableToggle : true,
toggleHandler : function(btn, state) {
if (state) {
btn.setIcon('resources/images/icons/16Icons/157.png');
SetCookie('theme_def', 'blue');
Ext.util.CSS.swapStyleSheet('theme','resources/css/ext-all.css');
}
else {
btn.setIcon('resources/images/icons/16Icons/163.png');
SetCookie('theme_def', 'gray');
Ext.util.CSS.swapStyleSheet('theme','resources/css/ext-all-gray.css');
}
}
});
Ext.create('Ext.Button', {
text : '首选项',
iconCls : 'config24Icon',
iconAlign : 'left',
scale : 'medium',
width : 100,
tooltip : '<span style="font-size:12px">首选项设置</span>',
pressed : true,
renderTo : 'configDiv',
menu : mainMenu
});
Ext.create('Ext.Button', {
iconCls : 'exit24Icon',
iconAlign : 'left',
scale : 'medium',
text: '退出',
width : 60,
tooltip : '切换用户,安全退出系统',
pressed : true,
arrowAlign : 'right',
renderTo : 'closeDiv',
handler : function() {
window.location.href = 'j_spring_security_logout';
}
});
//设置皮肤
initTheme();
}
}); | zz-ms | trunk/zz-ms-v1.0/WebContent/app.js | JavaScript | asf20 | 3,928 |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
String rootPath=request.getContextPath();
request.setAttribute("ctx",request.getContextPath());
%>
<script type="text/javascript">
var default_tab_title = "个人中心";
var rootPath = '<%=rootPath%>';
var imgDir = rootPath+'/images/';
</script> | zz-ms | trunk/zz-ms-v1.0/WebContent/common/variable.jsp | Java Server Pages | asf20 | 351 |
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> | zz-ms | trunk/zz-ms-v1.0/WebContent/common/taglibs.jsp | Java Server Pages | asf20 | 269 |
<!-- HTTP 1.1 -->
<meta http-equiv="Cache-Control" content="no-store"/>
<!-- HTTP 1.0 -->
<meta http-equiv="Pragma" content="no-cache"/>
<!-- Prevents caching at the Proxy Server -->
<meta http-equiv="Expires" content="0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | zz-ms | trunk/zz-ms-v1.0/WebContent/common/meta.jsp | Java Server Pages | asf20 | 299 |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<link rel="stylesheet" type="text/css" href="${ctx}/resources/css/ext-all.css">
<script type="text/javascript" src="${ctx}/extjs/ext-all-dev.js"></script>
<script type="text/javascript" src="${ctx}/app/comm/utility.js"></script> | zz-ms | trunk/zz-ms-v1.0/WebContent/common/scripts.jsp | Java Server Pages | asf20 | 321 |
//============================================================================
// Name : Login.cpp
// Author : zhou zhao
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <vector>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include "ServerRecord.h"
#define SERVER_PORT "3490" //port number the server will listening to
#define SUPERNODE_INFO "Accepted#127.0.0.1 3500" //IP and port number of supernode the server will send
#define SUPER_PORT "3600"
#define BACKLOG 10 //the maximum pending connections in the queue
#define MAXLINE 100
#define MAXDATASIZE 100
using namespace std;
vector<ServerRecord*> userDB;
/*
//callback function when parent process receive signal from the child
void sigchld_handler(int signal){
while(waitpid(-1, NULL, WNOHANG) > 0);
}
*/
//translate general socket address to IPv4 or IPv6 address
void* sockAddrTranslate(struct sockaddr* sockAddr){
if(sockAddr->sa_family == AF_INET){
return &(((struct sockaddr_in*)sockAddr)->sin_addr);
}else{
return &(((struct sockaddr_in6*)sockAddr)->sin6_addr);
}
}
bool checkLogin(){
for(unsigned int i=0; i<userDB.size(); i++){
if(userDB[i]->getLogin() == false){
return false;
}
}
return true;
}
int main(int argc, char* argv[]) {
char fileName[] = "UserPassMatch.txt";
FILE* fileHandle;
char buffer[MAXLINE];
char username[MAXLINE];
char password[MAXLINE];
char portnumber[MAXLINE];
ServerRecord* recordPtr;
int sockFD;
struct addrinfo hints, *serveInfo, *servePtr;
int returnValue;
int yes = 1;
// struct sigaction sigact;
struct sockaddr_storage clientAddr;
socklen_t clientAddrSize;
int sockFDNew;
char ipAddr[INET6_ADDRSTRLEN];
int numByteSend, numByteRec;
char data[MAXDATASIZE];
string user, pass, portnum;
//check the hostname of supernode is import
if(argc != 2){
perror("usage: ./Login supernode");
exit(1);
}
//open user record file
if((fileHandle = fopen(fileName, "r")) == NULL){
perror("server: fopen has error");
exit(1);
}
//construct the user DB
while(fgets(buffer, MAXLINE, fileHandle) != NULL){
if(sscanf(buffer, "%s %s", username, password) == 2){
recordPtr = new ServerRecord();
recordPtr->setUsername(string(username));
recordPtr->setPassword(string(password));
recordPtr->setLogin(false);
userDB.push_back(recordPtr);
}else{
perror("server: user pass format is not correct");
}
}
//close user record file
fclose(fileHandle);
//print the user DB
for(unsigned int i=0; i<userDB.size(); i++){
cout<<"username:"<<userDB[i]->getUsername()<<" password:"
<<userDB[i]->getPassword()<<endl;
}
//prepare IP address information
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
//get server IP address information
if((returnValue = getaddrinfo(NULL, SERVER_PORT, &hints, &serveInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s.\n", gai_strerror(returnValue));
exit(1);
}
for(servePtr = serveInfo; servePtr != NULL; servePtr = servePtr->ai_next){
//create a socket
if((sockFD = socket(servePtr->ai_family, servePtr->ai_socktype,
servePtr->ai_protocol)) == -1){
perror("server: socket has error");
continue;
}
//setup socket option
if(setsockopt(sockFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1){
perror("server: setsockopt has error");
exit(1);
}
//bind the socket
if(bind(sockFD, servePtr->ai_addr, servePtr->ai_addrlen) == -1){
close(sockFD);
perror("server: bind has error");
continue;
}
break;
}
if(servePtr == NULL){
perror("server: servePtr is NULL");
exit(1);
}
freeaddrinfo(serveInfo);
if(listen(sockFD, BACKLOG) == -1){
perror("server: listen has error");
exit(1);
}
/*
//setup signal between parent and child process
sigact.sa_handler = sigchld_handler;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = SA_RESTART;
//register callback function for process signaling
if(sigaction(SIGCHLD, &sigact, NULL) == -1){
perror("server: sigaction has error.");
exit(1);
}
*/
cout<<"login server: waiting for client connections ..."<<endl;
//accept loop
while(!checkLogin()){
clientAddrSize = sizeof(clientAddr);
sockFDNew = accept(sockFD, (struct sockaddr*)&clientAddr, &clientAddrSize);
if(sockFDNew == -1){
perror("server: accept has error");
continue; //continue to serve next client
}
inet_ntop(clientAddr.ss_family, sockAddrTranslate((struct sockaddr*)&clientAddr),
ipAddr, sizeof(ipAddr));
cout<<"server: got connection from "<<ipAddr<<endl;
if((numByteRec = recv(sockFDNew, data, MAXDATASIZE-1, 0)) == -1){
perror("server: recv has error");
exit(1);
}
data[numByteRec] = '\0';
cout<<"server: data received is "<<data<<endl;
if(sscanf(data, "%s %s %s", username, password, portnumber) == 3){
user = string(username).erase(0, 6);
pass = string(password);
portnum = string(portnumber);
}else{
perror("server: username/password is missing");
}
for(unsigned int i=0; i<userDB.size(); i++){
if(userDB[i]->getUsername().compare(user) == 0){
if(userDB[i]->getPassword().compare(pass) == 0){
if((numByteSend = send(sockFDNew, SUPERNODE_INFO, sizeof(SUPERNODE_INFO), 0)) == -1){
perror("server: fail to send acceptance");
}
userDB[i]->setIPAddr(string(ipAddr));
userDB[i]->setLogin(true);
userDB[i]->setPortNum(portnum);
}
}
}
close(sockFDNew);
}
close(sockFD);
for(unsigned int i=0; i<userDB.size(); i++){
cout<<userDB[i]->getUsername()<<" "<<userDB[i]->getIPAddr()<<" "<<userDB[i]->getPortNum()<<endl;
}
cout<<"Phase 1 is complete"<<endl;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((returnValue = getaddrinfo(argv[1], SUPER_PORT, &hints, &serveInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(returnValue));
exit(1);
}
for(servePtr = serveInfo; servePtr != NULL; servePtr = servePtr->ai_next){
//construct a socket
if((sockFD = socket(servePtr->ai_family, servePtr->ai_socktype,
servePtr->ai_protocol)) == -1){
perror("server: socket has error");
continue;
}
//connect the socket
if(connect(sockFD, servePtr->ai_addr, servePtr->ai_addrlen) == -1){
close(sockFD);
perror("server: connect has error");
continue;
}
break;
}
if(servePtr == NULL){
perror("server: serverPtr is NULL");
exit(1);
}
//print connected supernode info
inet_ntop(servePtr->ai_family, sockAddrTranslate((struct sockaddr*)servePtr->ai_addr),
ipAddr, sizeof(ipAddr));
cout<<"server: connecting to supernode "<<ipAddr<<endl;
freeaddrinfo(serveInfo);
for(unsigned int i=0; i<userDB.size(); i++){
if((numByteSend = send(sockFD, (userDB[i]->getUsername()+string(" ")+userDB[i]->getIPAddr()+string(" ")+
userDB[i]->getPortNum()+string("\n")).c_str(),
userDB[i]->getUsername().size()+userDB[i]->getIPAddr().size()+userDB[i]->getPortNum().size()+3, 0)) == -1){
perror("server: send has error");
exit(1);
}
}
cout<<"Phase 2 is complete"<<endl;
return 0;
}
| zzfall2011ee450 | Login.cpp | C++ | gpl3 | 7,393 |
/*
* SuperRecord.h
*
* Created on: Nov 12, 2011
* Author: zhouzhao
*/
#ifndef SUPERRECORD_H_
#define SUPERRECORD_H_
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
using namespace std;
class SuperRecord {
private:
string username;
string ipaddr;
string port;
int sockfd;
struct addrinfo info;
public:
SuperRecord();
virtual ~SuperRecord();
void setUsername(string username);
string getUsername(void);
void setIPAddr(string ipaddr);
string getIPAddr(void);
void setPort(string port);
string getPort(void);
void setSockfd(int sockfd);
int getSockfd(void);
void setAddrInfo(struct addrinfo* p);
addrinfo* getAddrInfo(void);
};
#endif /* SUPERRECORD_H_ */
| zzfall2011ee450 | SuperRecord.h | C++ | gpl3 | 727 |
//============================================================================
// Name : User.cpp
// Author : zhou zhao
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iostream>
#define SERVERPORT "3490" //server port client will connect to
#define MAXDATASIZE 100
#define MAXLINE 100
using namespace std;
//translate general socket address to IPv4 or IPv6 address
void* sockAddrTranslate(struct sockaddr* sockAddr){
if(sockAddr->sa_family == AF_INET){
return &(((struct sockaddr_in*)sockAddr)->sin_addr);
}else{
return &(((struct sockaddr_in6*)sockAddr)->sin6_addr);
}
}
int main(int argc, char* argv[]) {
FILE* fileHandle;
char buffer[MAXLINE];
char username[MAXLINE];
char password[MAXLINE];
char portnumber[MAXLINE];
string user, pass, portnum, login;
int sockFD;
struct addrinfo hints, *serveInfo, *servePtr;
int returnValue;
char ipAddr[INET6_ADDRSTRLEN];
char data[MAXDATASIZE];
int numByteRecv;
int numByteSend;
string superIP, superPort;
char supernodeIP[MAXLINE];
char supernodePort[MAXLINE];
struct sockaddr_storage superAddr;
socklen_t superAddrSize;
//check the hostname of server is import
if(argc != 4){
perror("usage: ./Users serverIP UserPass.txt UserText.txt");
exit(1);
}
//open user pass file
if((fileHandle = fopen(argv[2], "r")) == NULL){
perror("client: fopen has error");
exit(1);
}
//import user pass information
while(fgets(buffer, MAXLINE, fileHandle) != NULL){
if(sscanf(buffer, "%s %s %s", username, password, portnumber) == 3){
user = string(username);
pass = string(password);
portnum = string(portnumber);
cout<<"username:"<<user<<" password:"<<pass<<" portnumber:"<<portnum<<endl;
}
}
fclose(fileHandle); //close user pass file
//prepare address info
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((returnValue = getaddrinfo(argv[1], SERVERPORT, &hints, &serveInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(returnValue));
exit(1);
}
for(servePtr = serveInfo; servePtr != NULL; servePtr = servePtr->ai_next){
//construct a socket
if((sockFD = socket(servePtr->ai_family, servePtr->ai_socktype,
servePtr->ai_protocol)) == -1){
perror("client: socket has error");
continue;
}
//connect socket
if(connect(sockFD, servePtr->ai_addr, servePtr->ai_addrlen) == -1){
close(sockFD);
perror("client: connect has error");
continue;
}
break;
}
if(servePtr == NULL){
perror("client: servePtr is NULL");
exit(1);
}
//print connected server info
inet_ntop(servePtr->ai_family, sockAddrTranslate((struct sockaddr*)servePtr->ai_addr),
ipAddr, sizeof(ipAddr));
cout<<"client: connecting to server "<<ipAddr<<endl;
freeaddrinfo(serveInfo);
login = user.insert(0, "Login#")+" "+pass+" "+portnum;
if((numByteSend = send(sockFD, login.c_str(), login.size(), 0)) == -1){
perror("client: send has error");
exit(1);
}
if((numByteRecv = recv(sockFD, data, MAXDATASIZE-1, 0)) == -1){
perror("client: recv has error");
exit(1);
}
data[numByteRecv] = '\0';
string temp = string(data);
cout<<temp<<endl;
if(temp.compare(0, 9, string("Accepted#")) == 0){
if(sscanf(data, "%s %s", supernodeIP, supernodePort) == 2){
superIP = string(supernodeIP).erase(0, 9);
superPort = string(supernodePort);
cout<<"supernodeIP:"<<superIP<<" supernodePort:"<<superPort<<endl;
}
}
close(sockFD);
cout<<"client will sleep ..."<<endl;
sleep(5);
cout<<"client is wake up"<<endl;
//open user text file
if((fileHandle = fopen(argv[3], "r")) == NULL){
perror("client: fopen has error");
exit(1);
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if((returnValue = getaddrinfo(superIP.c_str(), superPort.c_str(),
&hints, &serveInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(returnValue));
exit(1);
}
for(servePtr = serveInfo; servePtr != NULL; servePtr = servePtr->ai_next){
if((sockFD = socket(servePtr->ai_family, servePtr->ai_socktype,
servePtr->ai_protocol)) == -1){
perror("client: socket has error");
continue;
}
break;
}
if(servePtr == NULL){
perror("client: fail to bind UDP socket");
exit(1);
}
while(fgets(buffer, MAXLINE, fileHandle) != NULL){
cout<<buffer<<endl;
if((numByteSend = sendto(sockFD, buffer, strlen(buffer), 0,
servePtr->ai_addr, servePtr->ai_addrlen)) == -1){
perror("client: sendto has error");
exit(1);
}
}
fclose(fileHandle); //close user text file
freeaddrinfo(serveInfo);
close(sockFD);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
if((returnValue = getaddrinfo(NULL, portnumber, &hints, &serveInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(returnValue));
exit(1);
}
for(servePtr = serveInfo; servePtr != NULL; servePtr = servePtr->ai_next){
if((sockFD = socket(servePtr->ai_family, servePtr->ai_socktype, servePtr->ai_protocol)) == -1){
perror("client: socket has error");
continue;
}
if(bind(sockFD, servePtr->ai_addr, servePtr->ai_addrlen) == -1){
close(sockFD);
perror("client: bind has error");
continue;
}
break;
}
if(servePtr == NULL){
perror("client: servePtr is NULL");
exit(1);
}
freeaddrinfo(serveInfo);
superAddrSize = sizeof(superAddr);
cout<<"client is waiting for data from supernode"<<endl;
while(1){
if((numByteRecv = recvfrom(sockFD, data, MAXDATASIZE-1, 0,
(struct sockaddr*)&superAddr, &superAddrSize)) == -1){
perror("client: recvfrom has error");
exit(1);
}
data[numByteRecv] = '\0';
cout<<data<<endl;
}
return 0;
}
| zzfall2011ee450 | User.cpp | C++ | gpl3 | 6,060 |
/*
* ServerRecord.h
*
* Created on: Nov 5, 2011
* Author: zhouzhao
*/
#ifndef SERVERRECORD_H_
#define SERVERRECORD_H_
#include <string>
using namespace std;
class ServerRecord {
private:
unsigned int userid;
string username;
string password;
string ipaddr;
string portnum;
bool login;
public:
ServerRecord();
virtual ~ServerRecord();
void setUsername(string username);
string getUsername(void);
void setPassword(string password);
string getPassword(void);
void setIPAddr(string ipaddr);
string getIPAddr(void);
void setPortNum(string portnum);
string getPortNum(void);
void setLogin(bool login);
bool getLogin(void);
void setUserID(unsigned int userid);
unsigned int getUserID(void);
};
#endif /* SERVERRECORD_H_ */
| zzfall2011ee450 | ServerRecord.h | C++ | gpl3 | 755 |
//============================================================================
// Name : Supernode.cpp
// Author : zhou zhao
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <vector>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include "SuperRecord.h"
#define SUPER_PORT_SERVER "3600" //port number the supernode will listen from server
#define SUPER_PORT_CLIENT "3500" //port number the supernode will listen from client
#define BACKLOG 10
#define MAXLINE 100
#define MAXDATASIZE 100
using namespace std;
vector<SuperRecord*> loginDB;
//translate general socket address to IPv4 or IPv6 address
void* sockAddrTranslate(struct sockaddr* sockAddr){
if(sockAddr->sa_family == AF_INET){
return &(((struct sockaddr_in*)sockAddr)->sin_addr);
}else{
return &(((struct sockaddr_in6*)sockAddr)->sin6_addr);
}
}
void constructSock(){
int sockfd, rv;
struct addrinfo hints, *superInfo, *superPtr;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
for(unsigned int i=0; i<loginDB.size(); i++){
if((rv = getaddrinfo(loginDB[i]->getIPAddr().c_str(), loginDB[i]->getPort().c_str(),
&hints, &superInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
for(superPtr = superInfo; superPtr != NULL; superPtr = superPtr->ai_next){
if((sockfd = socket(superPtr->ai_family, superPtr->ai_socktype,
superPtr->ai_protocol)) == -1){
perror("supernode: socket has error");
continue;
}
break;
}
if(superPtr == NULL){
perror("supernode: superPtr is NULL");
exit(1);
}
loginDB[i]->setSockfd(sockfd);
loginDB[i]->setAddrInfo(superPtr);
// freeaddrinfo(superInfo);
}
}
int main() {
SuperRecord* recordPtr;
int sockFD, sockFDNew;
struct addrinfo hints, *superInfo, *superPtr;
int returnValue, yes = 1;
struct sockaddr_storage serverAddr;
socklen_t serverAddrSize;
char ipAddr[INET6_ADDRSTRLEN];
int numByteRec, numByteSend;
char data[MAXDATASIZE];
char fileName1[] = "UserLogin.txt";
char fileName2[] = "UserText.txt";
FILE* fileHandle;
char buffer[MAXLINE];
char username[MAXLINE];
char ipaddress[MAXLINE];
char portnumber[MAXLINE];
string target, message;
fpos_t fpos;
//prepare IP address info
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
//get IP address info
if((returnValue = getaddrinfo(NULL, SUPER_PORT_SERVER, &hints, &superInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s.\n", gai_strerror(returnValue));
exit(1);
}
for(superPtr = superInfo; superPtr != NULL; superPtr = superPtr->ai_next){
//create a socket
if((sockFD = socket(superPtr->ai_family, superPtr->ai_socktype,
superPtr->ai_protocol)) == -1){
perror("supernode: socket has error");
continue;
}
//setup socket option
if(setsockopt(sockFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1){
perror("supernode: setsocketopt has error");
exit(1);
}
//bind socket
if(bind(sockFD, superPtr->ai_addr, superPtr->ai_addrlen) == -1){
close(sockFD);
perror("supernode: bind has error");
continue;
}
break;
}
if(superPtr == NULL){
perror("supernode: superPtr is NULL");
exit(1);
}
freeaddrinfo(superInfo);
if(listen(sockFD, BACKLOG) == -1){
perror("supernode: listen has error");
exit(1);
}
cout<<"supernode: waiting for server connections ..."<<endl;
serverAddrSize = sizeof(serverAddr);
sockFDNew = accept(sockFD, (struct sockaddr*)&serverAddr, &serverAddrSize);
if(sockFDNew == -1){
perror("supernode: accept has error");
exit(1);
}
inet_ntop(serverAddr.ss_family, sockAddrTranslate((struct sockaddr*)&serverAddr),
ipAddr, sizeof(ipAddr));
cout<<"supernode: got server connection from "<<ipAddr<<endl;
if((numByteRec = recv(sockFDNew, data, MAXDATASIZE-1, 0)) == -1){
perror("supernode: recv has error");
exit(1);
}
data[numByteRec] = '\0';
//open user login file
if((fileHandle = fopen(fileName1, "w+")) == NULL){
perror("supernode: fopen has error");
exit(1);
}
fgetpos(fileHandle, &fpos);
if(fputs(data, fileHandle) == EOF){
perror("supernode: fputs has error");
exit(1);
}
fsetpos(fileHandle, &fpos);
cout<<"jump into while loop"<<endl;
//construct login user DB
while(fgets(buffer, MAXLINE, fileHandle) != NULL){
if(sscanf(buffer, "%s %s %s", username, ipaddress, portnumber) == 3){
recordPtr = new SuperRecord();
recordPtr->setUsername(string(username));
recordPtr->setIPAddr(string(ipaddress));
recordPtr->setPort(string(portnumber));
loginDB.push_back(recordPtr);
}else{
perror("supernode: user login format is not correct");
}
}
cout<<"loginDB has sizeof "<<loginDB.size()<<endl;
for(unsigned int i=0; i<loginDB.size(); i++){
cout<<loginDB[i]->getUsername()<<" "<<loginDB[i]->getIPAddr()<<" "<<loginDB[i]->getPort()<<endl;
}
fclose(fileHandle);
close(sockFD);
close(sockFDNew);
constructSock();
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
if((returnValue = getaddrinfo(NULL, SUPER_PORT_CLIENT, &hints, &superInfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(returnValue));
exit(1);
}
for(superPtr = superInfo; superPtr != NULL; superPtr = superPtr->ai_next){
if((sockFD = socket(superPtr->ai_family, superPtr->ai_socktype, superPtr->ai_protocol)) == -1){
perror("supernode: socket has error");
continue;
}
if(bind(sockFD, superPtr->ai_addr, superPtr->ai_addrlen) == -1){
close(sockFD);
perror("supernode: bind has error");
continue;
}
break;
}
if(superPtr == NULL){
perror("supernode: superPtr is NULL");
exit(1);
}
freeaddrinfo(superInfo);
cout<<"supernode is waiting for data from client"<<endl;
sleep(10);
while(1){
serverAddrSize = sizeof(serverAddr);
if((numByteRec = recvfrom(sockFD, data, MAXDATASIZE-1, 0,
(struct sockaddr*)&serverAddr, &serverAddrSize)) == -1){
perror("supernode: recvfrom has error");
exit(1);
}
data[numByteRec] = '\0';
inet_ntop(serverAddr.ss_family, sockAddrTranslate((struct sockaddr*)&serverAddr),
ipAddr, sizeof(ipAddr));
cout<<"supernode: got client connection from "<<ipAddr<<endl;
cout<<data<<endl;
if((fileHandle = fopen(fileName2, "w+")) == NULL){
perror("supernode: fopen has error");
exit(1);
}
fgetpos(fileHandle, &fpos);
if(fputs(data, fileHandle) == EOF){
perror("supernode: fputs has error");
exit(1);
}
fsetpos(fileHandle, &fpos);
while(fgets(buffer, MAXLINE, fileHandle) != NULL){
target = string(buffer).substr(0, 6);
message = string(buffer).erase(0, 7);
for(unsigned int i=0; i<loginDB.size(); i++){
if(loginDB[i]->getUsername().compare(target) == 0){
if((numByteSend = sendto(loginDB[i]->getSockfd(), message.c_str(),
message.size(), 0, loginDB[i]->getAddrInfo()->ai_addr,
loginDB[i]->getAddrInfo()->ai_addrlen)) == -1){
perror("supernode: sendto has error");
exit(1);
}
cout<<"number of bytes send is "<<numByteSend<<endl;
}
}
}
fclose(fileHandle);
}
return 0;
}
| zzfall2011ee450 | Supernode.cpp | C++ | gpl3 | 7,454 |
cmake_minimum_required(VERSION 2.8)
project(vjson)
add_executable(vjson_test block_allocator.cpp json.cpp main.cpp)
| zzuseme-vjson | CMakeLists.txt | CMake | mit | 119 |
#ifndef BLOCK_ALLOCATOR_H
#define BLOCK_ALLOCATOR_H
class block_allocator
{
private:
struct block
{
size_t size;
size_t used;
char *buffer;
block *next;
};
block *m_head;
size_t m_blocksize;
block_allocator(const block_allocator &);
block_allocator &operator=(block_allocator &);
public:
block_allocator(size_t blocksize);
~block_allocator();
// exchange contents with rhs
void swap(block_allocator &rhs);
// allocate memory
void *malloc(size_t size);
// free all allocated blocks
void free();
};
#endif
| zzuseme-vjson | block_allocator.h | C++ | mit | 570 |
#include <memory.h>
#include "json.h"
// true if character represent a digit
#define IS_DIGIT(c) (c >= '0' && c <= '9')
// convert string to integer
char *atoi(char *first, char *last, int *out)
{
int sign = 1;
if (first != last)
{
if (*first == '-')
{
sign = -1;
++first;
}
else if (*first == '+')
{
++first;
}
}
int result = 0;
for (; first != last && IS_DIGIT(*first); ++first)
{
result = 10 * result + (*first - '0');
}
*out = result * sign;
return first;
}
// convert hexadecimal string to unsigned integer
char *hatoui(char *first, char *last, unsigned int *out)
{
unsigned int result = 0;
for (; first != last; ++first)
{
int digit;
if (IS_DIGIT(*first))
{
digit = *first - '0';
}
else if (*first >= 'a' && *first <= 'f')
{
digit = *first - 'a' + 10;
}
else if (*first >= 'A' && *first <= 'F')
{
digit = *first - 'A' + 10;
}
else
{
break;
}
result = 16 * result + digit;
}
*out = result;
return first;
}
// convert string to floating point
char *atof(char *first, char *last, float *out)
{
// sign
float sign = 1;
if (first != last)
{
if (*first == '-')
{
sign = -1;
++first;
}
else if (*first == '+')
{
++first;
}
}
// integer part
float result = 0;
for (; first != last && IS_DIGIT(*first); ++first)
{
result = 10 * result + (*first - '0');
}
// fraction part
if (first != last && *first == '.')
{
++first;
float inv_base = 0.1f;
for (; first != last && IS_DIGIT(*first); ++first)
{
result += (*first - '0') * inv_base;
inv_base *= 0.1f;
}
}
// result w\o exponent
result *= sign;
// exponent
bool exponent_negative = false;
int exponent = 0;
if (first != last && (*first == 'e' || *first == 'E'))
{
++first;
if (*first == '-')
{
exponent_negative = true;
++first;
}
else if (*first == '+')
{
++first;
}
for (; first != last && IS_DIGIT(*first); ++first)
{
exponent = 10 * exponent + (*first - '0');
}
}
if (exponent)
{
float power_of_ten = 10;
for (; exponent > 1; exponent--)
{
power_of_ten *= 10;
}
if (exponent_negative)
{
result /= power_of_ten;
}
else
{
result *= power_of_ten;
}
}
*out = result;
return first;
}
json_value *json_alloc(block_allocator *allocator)
{
json_value *value = (json_value *)allocator->malloc(sizeof(json_value));
memset(value, 0, sizeof(json_value));
return value;
}
void json_append(json_value *lhs, json_value *rhs)
{
rhs->parent = lhs;
if (lhs->last_child)
{
lhs->last_child = lhs->last_child->next_sibling = rhs;
}
else
{
lhs->first_child = lhs->last_child = rhs;
}
}
#define ERROR(it, desc)\
*error_pos = it;\
*error_desc = (char *)desc;\
*error_line = 1 - escaped_newlines;\
for (char *c = it; c != source; --c)\
if (*c == '\n') ++*error_line;\
return 0
#define CHECK_TOP() if (!top) {ERROR(it, "Unexpected character");}
json_value *json_parse(char *source, char **error_pos, char **error_desc, int *error_line, block_allocator *allocator)
{
json_value *root = 0;
json_value *top = 0;
char *name = 0;
char *it = source;
int escaped_newlines = 0;
while (*it)
{
switch (*it)
{
case '{':
case '[':
{
// create new value
json_value *object = json_alloc(allocator);
// name
object->name = name;
name = 0;
// type
object->type = (*it == '{') ? JSON_OBJECT : JSON_ARRAY;
// skip open character
++it;
// set top and root
if (top)
{
json_append(top, object);
}
else if (!root)
{
root = object;
}
else
{
ERROR(it, "Second root. Only one root allowed");
}
top = object;
}
break;
case '}':
case ']':
{
if (!top || top->type != ((*it == '}') ? JSON_OBJECT : JSON_ARRAY))
{
ERROR(it, "Mismatch closing brace/bracket");
}
// skip close character
++it;
// set top
top = top->parent;
}
break;
case ':':
if (!top || top->type != JSON_OBJECT)
{
ERROR(it, "Unexpected character");
}
++it;
break;
case ',':
CHECK_TOP();
++it;
break;
case '"':
{
CHECK_TOP();
// skip '"' character
++it;
char *first = it;
char *last = it;
while (*it)
{
if ((unsigned char)*it < '\x20')
{
ERROR(first, "Control characters not allowed in strings");
}
else if (*it == '\\')
{
switch (it[1])
{
case '"':
*last = '"';
break;
case '\\':
*last = '\\';
break;
case '/':
*last = '/';
break;
case 'b':
*last = '\b';
break;
case 'f':
*last = '\f';
break;
case 'n':
*last = '\n';
++escaped_newlines;
break;
case 'r':
*last = '\r';
break;
case 't':
*last = '\t';
break;
case 'u':
{
unsigned int codepoint;
if (hatoui(it + 2, it + 6, &codepoint) != it + 6)
{
ERROR(it, "Bad unicode codepoint");
}
if (codepoint <= 0x7F)
{
*last = (char)codepoint;
}
else if (codepoint <= 0x7FF)
{
*last++ = (char)(0xC0 | (codepoint >> 6));
*last = (char)(0x80 | (codepoint & 0x3F));
}
else if (codepoint <= 0xFFFF)
{
*last++ = (char)(0xE0 | (codepoint >> 12));
*last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F));
*last = (char)(0x80 | (codepoint & 0x3F));
}
}
it += 4;
break;
default:
ERROR(first, "Unrecognized escape sequence");
}
++last;
it += 2;
}
else if (*it == '"')
{
*last = 0;
++it;
break;
}
else
{
*last++ = *it++;
}
}
if (!name && top->type == JSON_OBJECT)
{
// field name in object
name = first;
}
else
{
// new string value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
object->type = JSON_STRING;
object->string_value = first;
json_append(top, object);
}
}
break;
case 'n':
case 't':
case 'f':
{
CHECK_TOP();
// new null/bool value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
// null
if (it[0] == 'n' && it[1] == 'u' && it[2] == 'l' && it[3] == 'l')
{
object->type = JSON_NULL;
it += 4;
}
// true
else if (it[0] == 't' && it[1] == 'r' && it[2] == 'u' && it[3] == 'e')
{
object->type = JSON_BOOL;
object->int_value = 1;
it += 4;
}
// false
else if (it[0] == 'f' && it[1] == 'a' && it[2] == 'l' && it[3] == 's' && it[4] == 'e')
{
object->type = JSON_BOOL;
object->int_value = 0;
it += 5;
}
else
{
ERROR(it, "Unknown identifier");
}
json_append(top, object);
}
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
CHECK_TOP();
// new number value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
object->type = JSON_INT;
char *first = it;
while (*it != '\x20' && *it != '\x9' && *it != '\xD' && *it != '\xA' && *it != ',' && *it != ']' && *it != '}')
{
if (*it == '.' || *it == 'e' || *it == 'E')
{
object->type = JSON_FLOAT;
}
++it;
}
if (object->type == JSON_INT && atoi(first, it, &object->int_value) != it)
{
ERROR(first, "Bad integer number");
}
if (object->type == JSON_FLOAT && atof(first, it, &object->float_value) != it)
{
ERROR(first, "Bad float number");
}
json_append(top, object);
}
break;
default:
ERROR(it, "Unexpected character");
}
// skip white space
while (*it == '\x20' || *it == '\x9' || *it == '\xD' || *it == '\xA')
{
++it;
}
}
if (top)
{
ERROR(it, "Not all objects/arrays have been properly closed");
}
return root;
}
| zzuseme-vjson | json.cpp | C++ | mit | 8,555 |
#include <memory.h>
#include <algorithm>
#include "block_allocator.h"
block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize)
{
}
block_allocator::~block_allocator()
{
while (m_head)
{
block *temp = m_head->next;
::free(m_head);
m_head = temp;
}
}
void block_allocator::swap(block_allocator &rhs)
{
std::swap(m_blocksize, rhs.m_blocksize);
std::swap(m_head, rhs.m_head);
}
void *block_allocator::malloc(size_t size)
{
if ((m_head && m_head->used + size > m_head->size) || !m_head)
{
// calc needed size for allocation
size_t alloc_size = std::max(sizeof(block) + size, m_blocksize);
// create new block
char *buffer = (char *)::malloc(alloc_size);
block *b = reinterpret_cast<block *>(buffer);
b->size = alloc_size;
b->used = sizeof(block);
b->buffer = buffer;
b->next = m_head;
m_head = b;
}
void *ptr = m_head->buffer + m_head->used;
m_head->used += size;
return ptr;
}
void block_allocator::free()
{
block_allocator(0).swap(*this);
}
| zzuseme-vjson | block_allocator.cpp | C++ | mit | 1,062 |
#ifndef JSON_H
#define JSON_H
#include "block_allocator.h"
enum json_type
{
JSON_NULL,
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_INT,
JSON_FLOAT,
JSON_BOOL,
};
struct json_value
{
json_value *parent;
json_value *next_sibling;
json_value *first_child;
json_value *last_child;
char *name;
union
{
char *string_value;
int int_value;
float float_value;
};
json_type type;
};
json_value *json_parse(char *source, char **error_pos, char **error_desc, int *error_line, block_allocator *allocator);
#endif
| zzuseme-vjson | json.h | C | mit | 565 |
#include <vector>
#include <stdio.h>
#include "json.h"
void populate_sources(const char *filter, std::vector<std::vector<char> > &sources)
{
char filename[256];
for (int i = 1; i < 64; ++i)
{
sprintf(filename, filter, i);
FILE *fp = fopen(filename, "rb");
if (fp)
{
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<char> buffer(size + 1);
fread (&buffer[0], 1, size, fp);
fclose(fp);
sources.push_back(buffer);
}
else
{
break;
}
}
printf("Loaded %d json files\n", sources.size());
}
#define IDENT(n) for (int i = 0; i < n; ++i) printf(" ")
void print(json_value *value, int ident = 0)
{
IDENT(ident);
if (value->name) printf("\"%s\" = ", value->name);
switch(value->type)
{
case JSON_NULL:
printf("null\n");
break;
case JSON_OBJECT:
case JSON_ARRAY:
printf(value->type == JSON_OBJECT ? "{\n" : "[\n");
for (json_value *it = value->first_child; it; it = it->next_sibling)
{
print(it, ident + 1);
}
IDENT(ident);
printf(value->type == JSON_OBJECT ? "}\n" : "]\n");
break;
case JSON_STRING:
printf("\"%s\"\n", value->string_value);
break;
case JSON_INT:
printf("%d\n", value->int_value);
break;
case JSON_FLOAT:
printf("%f\n", value->float_value);
break;
case JSON_BOOL:
printf(value->int_value ? "true\n" : "false\n");
break;
}
}
bool parse(char *source)
{
char *errorPos = 0;
char *errorDesc = 0;
int errorLine = 0;
block_allocator allocator(1 << 10);
json_value *root = json_parse(source, &errorPos, &errorDesc, &errorLine, &allocator);
if (root)
{
print(root);
return true;
}
printf("Error at line %d: %s\n%s\n\n", errorLine, errorDesc, errorPos);
return false;
}
int main(int argc, char **argv)
{
// Fail
printf("===FAIL===\n\n");
std::vector<std::vector<char> > sources;
populate_sources("test/fail%d.json", sources);
int passed = 0;
for (size_t i = 0; i < sources.size(); ++i)
{
printf("Parsing %d\n", i + 1);
if (parse(&sources[i][0]))
{
++passed;
}
}
printf("Passed %d from %d tests\n", passed, sources.size());
// Pass
sources.clear();
printf("\n===PASS===\n\n");
populate_sources("test/pass%d.json", sources);
passed = 0;
for (size_t i = 0; i < sources.size(); ++i)
{
printf("Parsing %d\n", i + 1);
if (parse(&sources[i][0]))
{
++passed;
}
}
printf("Passed %d from %d tests\n", passed, sources.size());
return 0;
}
| zzuseme-vjson | main.cpp | C++ | mit | 2,537 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Dapper
{
public class SqlBuilder
{
Dictionary<string, Clauses> data = new Dictionary<string, Clauses>();
int seq;
class Clause
{
public string Sql { get; set; }
public object Parameters { get; set; }
}
class Clauses : List<Clause>
{
string joiner;
string prefix;
string postfix;
public Clauses(string joiner, string prefix = "", string postfix = "")
{
this.joiner = joiner;
this.prefix = prefix;
this.postfix = postfix;
}
public string ResolveClauses(DynamicParameters p)
{
foreach (var item in this)
{
p.AddDynamicParams(item.Parameters);
}
return prefix + string.Join(joiner, this.Select(c => c.Sql)) + postfix;
}
}
public class Template
{
readonly string sql;
readonly SqlBuilder builder;
readonly object initParams;
int dataSeq = -1; // Unresolved
public Template(SqlBuilder builder, string sql, dynamic parameters)
{
this.initParams = parameters;
this.sql = sql;
this.builder = builder;
}
static System.Text.RegularExpressions.Regex regex =
new System.Text.RegularExpressions.Regex(@"\/\*\*.+\*\*\/", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
void ResolveSql()
{
if (dataSeq != builder.seq)
{
DynamicParameters p = new DynamicParameters(initParams);
rawSql = sql;
foreach (var pair in builder.data)
{
rawSql = rawSql.Replace("/**" + pair.Key + "**/", pair.Value.ResolveClauses(p));
}
parameters = p;
// replace all that is left with empty
rawSql = regex.Replace(rawSql, "");
dataSeq = builder.seq;
}
}
string rawSql;
object parameters;
public string RawSql { get { ResolveSql(); return rawSql; } }
public object Parameters { get { ResolveSql(); return parameters; } }
}
public SqlBuilder()
{
}
public Template AddTemplate(string sql, dynamic parameters = null)
{
return new Template(this, sql, parameters);
}
void AddClause(string name, string sql, object parameters, string joiner, string prefix = "", string postfix = "")
{
Clauses clauses;
if (!data.TryGetValue(name, out clauses))
{
clauses = new Clauses(joiner, prefix, postfix);
data[name] = clauses;
}
clauses.Add(new Clause { Sql = sql, Parameters = parameters });
seq++;
}
public SqlBuilder InnerJoin(string sql, dynamic parameters = null)
{
AddClause("innerjoin", sql, parameters, joiner: "\nINNER JOIN ", prefix: "\nINNER JOIN ", postfix: "\n");
return this;
}
public SqlBuilder LeftJoin(string sql, dynamic parameters = null)
{
AddClause("leftjoin", sql, parameters, joiner: "\nLEFT JOIN ", prefix: "\nLEFT JOIN ", postfix: "\n");
return this;
}
public SqlBuilder RightJoin(string sql, dynamic parameters = null)
{
AddClause("rightjoin", sql, parameters, joiner: "\nRIGHT JOIN ", prefix: "\nRIGHT JOIN ", postfix: "\n");
return this;
}
public SqlBuilder Where(string sql, dynamic parameters = null)
{
AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n");
return this;
}
public SqlBuilder OrderBy(string sql, dynamic parameters = null)
{
AddClause("orderby", sql, parameters, " , ", prefix: "ORDER BY ", postfix: "\n");
return this;
}
public SqlBuilder Select(string sql, dynamic parameters = null)
{
AddClause("select", sql, parameters, " , ", prefix: "", postfix: "\n");
return this;
}
public SqlBuilder AddParameters(dynamic parameters)
{
AddClause("--parameters", "", parameters, "");
return this;
}
public SqlBuilder Join(string sql, dynamic parameters = null)
{
AddClause("join", sql, parameters, joiner: "\nJOIN ", prefix: "\nJOIN ", postfix: "\n");
return this;
}
public SqlBuilder GroupBy(string sql, dynamic parameters = null)
{
AddClause("groupby", sql, parameters, joiner: " , ", prefix: "\nGROUP BY ", postfix: "\n");
return this;
}
public SqlBuilder Having(string sql, dynamic parameters = null)
{
AddClause("having", sql, parameters, joiner: "\nAND ", prefix: "HAVING ", postfix: "\n");
return this;
}
}
}
| zzfenglove-dapper | Dapper.SqlBuilder/SqlBuilder.cs | C# | asf20 | 5,437 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper.SqlBuilder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dapper.SqlBuilder")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("27491c26-c95d-44e5-b907-30559ef11265")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | Dapper.SqlBuilder/Properties/AssemblyInfo.cs | C# | asf20 | 1,410 |
using System;
using System.Reflection;
using System.Data.SqlClient;
namespace DapperTests_NET35
{
class Program
{
static void Main()
{
RunTests();
Console.WriteLine("(end of tests; press any key)");
Console.ReadKey();
}
public static readonly string connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True";
public static SqlConnection GetOpenConnection()
{
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
private static void RunTests()
{
var tester = new Tests();
foreach (var method in typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
}
}
}
}
| zzfenglove-dapper | DapperTests NET35/Program.cs | C# | asf20 | 1,069 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DapperTests NET35")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DapperTests NET35")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cad8d6dd-b2be-441c-a287-c45ecc772065")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | DapperTests NET35/Properties/AssemblyInfo.cs | C# | asf20 | 1,464 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Dapper")]
[assembly: AssemblyCopyright("Copyright © Sam Saffron 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("59080aa9-fa65-438f-ad2e-772d840effa9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.12.1.1")]
[assembly: AssemblyFileVersion("1.12.1.1")]
| zzfenglove-dapper | Dapper NET40/Properties/AssemblyInfo.cs | C# | asf20 | 1,496 |
/*
License: http://www.apache.org/licenses/LICENSE-2.0
Home page: http://code.google.com/p/dapper-dot-net/
Note: to build on C# 3.0 + .NET 3.5, include the CSHARP30 compiler symbol (and yes,
I know the difference between language and runtime versions; this is a compromise).
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace Dapper
{
/// <summary>
/// Dapper, a light weight object mapper for ADO.NET
/// </summary>
static partial class SqlMapper
{
/// <summary>
/// Implement this interface to pass an arbitrary db specific set of parameters to Dapper
/// </summary>
public partial interface IDynamicParameters
{
/// <summary>
/// Add all the parameters needed to the command just before it executes
/// </summary>
/// <param name="command">The raw command prior to execution</param>
/// <param name="identity">Information about the query</param>
void AddParameters(IDbCommand command, Identity identity);
}
/// <summary>
/// Implement this interface to pass an arbitrary db specific parameter to Dapper
/// </summary>
public interface ICustomQueryParameter
{
/// <summary>
/// Add the parameter needed to the command before it executes
/// </summary>
/// <param name="command">The raw command prior to execution</param>
/// <param name="name">Parameter name</param>
void AddParameter(IDbCommand command, string name);
}
/// <summary>
/// Implement this interface to change default mapping of reader columns to type memebers
/// </summary>
public interface ITypeMap
{
/// <summary>
/// Finds best constructor
/// </summary>
/// <param name="names">DataReader column names</param>
/// <param name="types">DataReader column types</param>
/// <returns>Matching constructor or default one</returns>
ConstructorInfo FindConstructor(string[] names, Type[] types);
/// <summary>
/// Gets mapping for constructor parameter
/// </summary>
/// <param name="constructor">Constructor to resolve</param>
/// <param name="columnName">DataReader column name</param>
/// <returns>Mapping implementation</returns>
IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName);
/// <summary>
/// Gets member mapping for column
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <returns>Mapping implementation</returns>
IMemberMap GetMember(string columnName);
}
/// <summary>
/// Implements this interface to provide custom member mapping
/// </summary>
public interface IMemberMap
{
/// <summary>
/// Source DataReader column name
/// </summary>
string ColumnName { get; }
/// <summary>
/// Target member type
/// </summary>
Type MemberType { get; }
/// <summary>
/// Target property
/// </summary>
PropertyInfo Property { get; }
/// <summary>
/// Target field
/// </summary>
FieldInfo Field { get; }
/// <summary>
/// Target constructor parameter
/// </summary>
ParameterInfo Parameter { get; }
}
static Link<Type, Action<IDbCommand, bool>> bindByNameCache;
static Action<IDbCommand, bool> GetBindByName(Type commandType)
{
if (commandType == null) return null; // GIGO
Action<IDbCommand, bool> action;
if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action))
{
return action;
}
var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
action = null;
ParameterInfo[] indexers;
MethodInfo setter;
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
&& ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0)
&& (setter = prop.GetSetMethod()) != null
)
{
var method = new DynamicMethod(commandType.Name + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) });
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, commandType);
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Callvirt, setter, null);
il.Emit(OpCodes.Ret);
action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>));
}
// cache it
Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action);
return action;
}
/// <summary>
/// This is a micro-cache; suitable when the number of terms is controllable (a few hundred, for example),
/// and strictly append-only; you cannot change existing values. All key matches are on **REFERENCE**
/// equality. The type is fully thread-safe.
/// </summary>
partial class Link<TKey, TValue> where TKey : class
{
public static bool TryGet(Link<TKey, TValue> link, TKey key, out TValue value)
{
while (link != null)
{
if ((object)key == (object)link.Key)
{
value = link.Value;
return true;
}
link = link.Tail;
}
value = default(TValue);
return false;
}
public static bool TryAdd(ref Link<TKey, TValue> head, TKey key, ref TValue value)
{
bool tryAgain;
do
{
var snapshot = Interlocked.CompareExchange(ref head, null, null);
TValue found;
if (TryGet(snapshot, key, out found))
{ // existing match; report the existing value instead
value = found;
return false;
}
var newNode = new Link<TKey, TValue>(key, value, snapshot);
// did somebody move our cheese?
tryAgain = Interlocked.CompareExchange(ref head, newNode, snapshot) != snapshot;
} while (tryAgain);
return true;
}
private Link(TKey key, TValue value, Link<TKey, TValue> tail)
{
Key = key;
Value = value;
Tail = tail;
}
public TKey Key { get; private set; }
public TValue Value { get; private set; }
public Link<TKey, TValue> Tail { get; private set; }
}
partial class CacheInfo
{
public DeserializerState Deserializer { get; set; }
public Func<IDataReader, object>[] OtherDeserializers { get; set; }
public Action<IDbCommand, object> ParamReader { get; set; }
private int hitCount;
public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
public void RecordHit() { Interlocked.Increment(ref hitCount); }
}
static int GetColumnHash(IDataReader reader)
{
unchecked
{
int colCount = reader.FieldCount, hash = colCount;
for (int i = 0; i < colCount; i++)
{ // binding code is only interested in names - not types
object tmp = reader.GetName(i);
hash = (hash * 31) + (tmp == null ? 0 : tmp.GetHashCode());
}
return hash;
}
}
struct DeserializerState
{
public readonly int Hash;
public readonly Func<IDataReader, object> Func;
public DeserializerState(int hash, Func<IDataReader, object> func)
{
Hash = hash;
Func = func;
}
}
/// <summary>
/// Called if the query cache is purged via PurgeQueryCache
/// </summary>
public static event EventHandler QueryCachePurged;
private static void OnQueryCachePurged()
{
var handler = QueryCachePurged;
if (handler != null) handler(null, EventArgs.Empty);
}
#if CSHARP30
private static readonly Dictionary<Identity, CacheInfo> _queryCache = new Dictionary<Identity, CacheInfo>();
// note: conflicts between readers and writers are so short-lived that it isn't worth the overhead of
// ReaderWriterLockSlim etc; a simple lock is faster
private static void SetQueryCache(Identity key, CacheInfo value)
{
lock (_queryCache) { _queryCache[key] = value; }
}
private static bool TryGetQueryCache(Identity key, out CacheInfo value)
{
lock (_queryCache) { return _queryCache.TryGetValue(key, out value); }
}
private static void PurgeQueryCacheByType(Type type)
{
lock (_queryCache)
{
var toRemove = _queryCache.Keys.Where(id => id.type == type).ToArray();
foreach (var key in toRemove)
_queryCache.Remove(key);
}
}
/// <summary>
/// Purge the query cache
/// </summary>
public static void PurgeQueryCache()
{
lock (_queryCache)
{
_queryCache.Clear();
}
OnQueryCachePurged();
}
#else
static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>();
private static void SetQueryCache(Identity key, CacheInfo value)
{
if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
{
CollectCacheGarbage();
}
_queryCache[key] = value;
}
private static void CollectCacheGarbage()
{
try
{
foreach (var pair in _queryCache)
{
if (pair.Value.GetHitCount() <= COLLECT_HIT_COUNT_MIN)
{
CacheInfo cache;
_queryCache.TryRemove(pair.Key, out cache);
}
}
}
finally
{
Interlocked.Exchange(ref collect, 0);
}
}
private const int COLLECT_PER_ITEMS = 1000, COLLECT_HIT_COUNT_MIN = 0;
private static int collect;
private static bool TryGetQueryCache(Identity key, out CacheInfo value)
{
if (_queryCache.TryGetValue(key, out value))
{
value.RecordHit();
return true;
}
value = null;
return false;
}
/// <summary>
/// Purge the query cache
/// </summary>
public static void PurgeQueryCache()
{
_queryCache.Clear();
OnQueryCachePurged();
}
private static void PurgeQueryCacheByType(Type type)
{
foreach (var entry in _queryCache)
{
CacheInfo cache;
if (entry.Key.type == type)
_queryCache.TryRemove(entry.Key, out cache);
}
}
/// <summary>
/// Return a count of all the cached queries by dapper
/// </summary>
/// <returns></returns>
public static int GetCachedSQLCount()
{
return _queryCache.Count;
}
/// <summary>
/// Return a list of all the queries cached by dapper
/// </summary>
/// <param name="ignoreHitCountAbove"></param>
/// <returns></returns>
public static IEnumerable<Tuple<string, string, int>> GetCachedSQL(int ignoreHitCountAbove = int.MaxValue)
{
var data = _queryCache.Select(pair => Tuple.Create(pair.Key.connectionString, pair.Key.sql, pair.Value.GetHitCount()));
if (ignoreHitCountAbove < int.MaxValue) data = data.Where(tuple => tuple.Item3 <= ignoreHitCountAbove);
return data;
}
/// <summary>
/// Deep diagnostics only: find any hash collisions in the cache
/// </summary>
/// <returns></returns>
public static IEnumerable<Tuple<int, int>> GetHashCollissions()
{
var counts = new Dictionary<int, int>();
foreach (var key in _queryCache.Keys)
{
int count;
if (!counts.TryGetValue(key.hashCode, out count))
{
counts.Add(key.hashCode, 1);
}
else
{
counts[key.hashCode] = count + 1;
}
}
return from pair in counts
where pair.Value > 1
select Tuple.Create(pair.Key, pair.Value);
}
#endif
static readonly Dictionary<Type, DbType> typeMap;
static SqlMapper()
{
typeMap = new Dictionary<Type, DbType>();
typeMap[typeof(byte)] = DbType.Byte;
typeMap[typeof(sbyte)] = DbType.SByte;
typeMap[typeof(short)] = DbType.Int16;
typeMap[typeof(ushort)] = DbType.UInt16;
typeMap[typeof(int)] = DbType.Int32;
typeMap[typeof(uint)] = DbType.UInt32;
typeMap[typeof(long)] = DbType.Int64;
typeMap[typeof(ulong)] = DbType.UInt64;
typeMap[typeof(float)] = DbType.Single;
typeMap[typeof(double)] = DbType.Double;
typeMap[typeof(decimal)] = DbType.Decimal;
typeMap[typeof(bool)] = DbType.Boolean;
typeMap[typeof(string)] = DbType.String;
typeMap[typeof(char)] = DbType.StringFixedLength;
typeMap[typeof(Guid)] = DbType.Guid;
typeMap[typeof(DateTime)] = DbType.DateTime;
typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;
typeMap[typeof(TimeSpan)] = DbType.Time;
typeMap[typeof(byte[])] = DbType.Binary;
typeMap[typeof(byte?)] = DbType.Byte;
typeMap[typeof(sbyte?)] = DbType.SByte;
typeMap[typeof(short?)] = DbType.Int16;
typeMap[typeof(ushort?)] = DbType.UInt16;
typeMap[typeof(int?)] = DbType.Int32;
typeMap[typeof(uint?)] = DbType.UInt32;
typeMap[typeof(long?)] = DbType.Int64;
typeMap[typeof(ulong?)] = DbType.UInt64;
typeMap[typeof(float?)] = DbType.Single;
typeMap[typeof(double?)] = DbType.Double;
typeMap[typeof(decimal?)] = DbType.Decimal;
typeMap[typeof(bool?)] = DbType.Boolean;
typeMap[typeof(char?)] = DbType.StringFixedLength;
typeMap[typeof(Guid?)] = DbType.Guid;
typeMap[typeof(DateTime?)] = DbType.DateTime;
typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset;
typeMap[typeof(TimeSpan?)] = DbType.Time;
typeMap[typeof(Object)] = DbType.Object;
}
/// <summary>
/// Configire the specified type to be mapped to a given db-type
/// </summary>
public static void AddTypeMap(Type type, DbType dbType)
{
typeMap[type] = dbType;
}
internal const string LinqBinary = "System.Data.Linq.Binary";
internal static DbType LookupDbType(Type type, string name)
{
DbType dbType;
var nullUnderlyingType = Nullable.GetUnderlyingType(type);
if (nullUnderlyingType != null) type = nullUnderlyingType;
if (type.IsEnum && !typeMap.ContainsKey(type))
{
type = Enum.GetUnderlyingType(type);
}
if (typeMap.TryGetValue(type, out dbType))
{
return dbType;
}
if (type.FullName == LinqBinary)
{
return DbType.Binary;
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return DynamicParameters.EnumerableMultiParameter;
}
throw new NotSupportedException(string.Format("The member {0} of type {1} cannot be used as a parameter value", name, type));
}
/// <summary>
/// Identity of a cached query in Dapper, used for extensability
/// </summary>
public partial class Identity : IEquatable<Identity>
{
internal Identity ForGrid(Type primaryType, int gridIndex)
{
return new Identity(sql, commandType, connectionString, primaryType, parametersType, null, gridIndex);
}
internal Identity ForGrid(Type primaryType, Type[] otherTypes, int gridIndex)
{
return new Identity(sql, commandType, connectionString, primaryType, parametersType, otherTypes, gridIndex);
}
/// <summary>
/// Create an identity for use with DynamicParameters, internal use only
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Identity ForDynamicParameters(Type type)
{
return new Identity(sql, commandType, connectionString, this.type, type, null, -1);
}
internal Identity(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType, Type[] otherTypes)
: this(sql, commandType, connection.ConnectionString, type, parametersType, otherTypes, 0)
{ }
private Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, Type[] otherTypes, int gridIndex)
{
this.sql = sql;
this.commandType = commandType;
this.connectionString = connectionString;
this.type = type;
this.parametersType = parametersType;
this.gridIndex = gridIndex;
unchecked
{
hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
hashCode = hashCode * 23 + commandType.GetHashCode();
hashCode = hashCode * 23 + gridIndex.GetHashCode();
hashCode = hashCode * 23 + (sql == null ? 0 : sql.GetHashCode());
hashCode = hashCode * 23 + (type == null ? 0 : type.GetHashCode());
if (otherTypes != null)
{
foreach (var t in otherTypes)
{
hashCode = hashCode * 23 + (t == null ? 0 : t.GetHashCode());
}
}
hashCode = hashCode * 23 + (connectionString == null ? 0 : SqlMapper.connectionStringComparer.GetHashCode(connectionString));
hashCode = hashCode * 23 + (parametersType == null ? 0 : parametersType.GetHashCode());
}
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return Equals(obj as Identity);
}
/// <summary>
/// The sql
/// </summary>
public readonly string sql;
/// <summary>
/// The command type
/// </summary>
public readonly CommandType? commandType;
/// <summary>
///
/// </summary>
public readonly int hashCode, gridIndex;
/// <summary>
///
/// </summary>
public readonly Type type;
/// <summary>
///
/// </summary>
public readonly string connectionString;
/// <summary>
///
/// </summary>
public readonly Type parametersType;
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return hashCode;
}
/// <summary>
/// Compare 2 Identity objects
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Identity other)
{
return
other != null &&
gridIndex == other.gridIndex &&
type == other.type &&
sql == other.sql &&
commandType == other.commandType &&
SqlMapper.connectionStringComparer.Equals(connectionString, other.connectionString) &&
parametersType == other.parametersType;
}
}
#if CSHARP30
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <returns>Number of rows affected</returns>
public static int Execute(this IDbConnection cnn, string sql, object param)
{
return Execute(cnn, sql, param, null, null, null);
}
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <returns>Number of rows affected</returns>
public static int Execute(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
{
return Execute(cnn, sql, param, transaction, null, null);
}
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <returns>Number of rows affected</returns>
public static int Execute(this IDbConnection cnn, string sql, object param, CommandType commandType)
{
return Execute(cnn, sql, param, null, null, commandType);
}
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <returns>Number of rows affected</returns>
public static int Execute(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
{
return Execute(cnn, sql, param, transaction, null, commandType);
}
/// <summary>
/// Executes a query, returning the data typed as per T
/// </summary>
/// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
/// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
/// </returns>
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param)
{
return Query<T>(cnn, sql, param, null, true, null, null);
}
/// <summary>
/// Executes a query, returning the data typed as per T
/// </summary>
/// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
/// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
/// </returns>
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
{
return Query<T>(cnn, sql, param, transaction, true, null, null);
}
/// <summary>
/// Executes a query, returning the data typed as per T
/// </summary>
/// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
/// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
/// </returns>
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, CommandType commandType)
{
return Query<T>(cnn, sql, param, null, true, null, commandType);
}
/// <summary>
/// Executes a query, returning the data typed as per T
/// </summary>
/// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
/// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
/// </returns>
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
{
return Query<T>(cnn, sql, param, transaction, true, null, commandType);
}
/// <summary>
/// Execute a command that returns multiple result sets, and access each in turn
/// </summary>
public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
{
return QueryMultiple(cnn, sql, param, transaction, null, null);
}
/// <summary>
/// Execute a command that returns multiple result sets, and access each in turn
/// </summary>
public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, CommandType commandType)
{
return QueryMultiple(cnn, sql, param, null, null, commandType);
}
/// <summary>
/// Execute a command that returns multiple result sets, and access each in turn
/// </summary>
public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
{
return QueryMultiple(cnn, sql, param, transaction, null, commandType);
}
#endif
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <returns>Number of rows affected</returns>
public static int Execute(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
IEnumerable multiExec = (object)param as IEnumerable;
Identity identity;
CacheInfo info = null;
if (multiExec != null && !(multiExec is string))
{
bool isFirst = true;
int total = 0;
using (var cmd = SetupCommand(cnn, transaction, sql, null, null, commandTimeout, commandType))
{
string masterSql = null;
foreach (var obj in multiExec)
{
if (isFirst)
{
masterSql = cmd.CommandText;
isFirst = false;
identity = new Identity(sql, cmd.CommandType, cnn, null, obj.GetType(), null);
info = GetCacheInfo(identity);
}
else
{
cmd.CommandText = masterSql; // because we do magic replaces on "in" etc
cmd.Parameters.Clear(); // current code is Add-tastic
}
info.ParamReader(cmd, obj);
total += cmd.ExecuteNonQuery();
}
}
return total;
}
// nice and simple
if ((object)param != null)
{
identity = new Identity(sql, commandType, cnn, null, (object)param == null ? null : ((object)param).GetType(), null);
info = GetCacheInfo(identity);
}
return ExecuteCommand(cnn, transaction, sql, (object)param == null ? null : info.ParamReader, (object)param, commandTimeout, commandType);
}
#if !CSHARP30
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
return Query<DapperRow>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType);
}
#else
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param) {
return Query(cnn, sql, param, null, true, null, null);
}
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction) {
return Query(cnn, sql, param, transaction, true, null, null);
}
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, CommandType? commandType) {
return Query(cnn, sql, param, null, true, null, commandType);
}
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType? commandType) {
return Query(cnn, sql, param, transaction, true, null, commandType);
}
/// <summary>
/// Return a list of dynamic objects, reader is closed after the call
/// </summary>
public static IEnumerable<IDictionary<string,object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType) {
return Query<IDictionary<string, object>>(cnn, sql, param, transaction, buffered, commandTimeout, commandType);
}
#endif
/// <summary>
/// Executes a query, returning the data typed as per T
/// </summary>
/// <remarks>the dynamic param may seem a bit odd, but this works around a major usability issue in vs, if it is Object vs completion gets annoying. Eg type new [space] get new object</remarks>
/// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
/// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
/// </returns>
public static IEnumerable<T> Query<T>(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
var data = QueryInternal<T>(cnn, sql, param as object, transaction, commandTimeout, commandType);
return buffered ? data.ToList() : data;
}
/// <summary>
/// Execute a command that returns multiple result sets, and access each in turn
/// </summary>
public static GridReader QueryMultiple(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
Identity identity = new Identity(sql, commandType, cnn, typeof(GridReader), (object)param == null ? null : ((object)param).GetType(), null);
CacheInfo info = GetCacheInfo(identity);
IDbCommand cmd = null;
IDataReader reader = null;
bool wasClosed = cnn.State == ConnectionState.Closed;
try
{
if (wasClosed) cnn.Open();
cmd = SetupCommand(cnn, transaction, sql, info.ParamReader, (object)param, commandTimeout, commandType);
reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);
var result = new GridReader(cmd, reader, identity);
wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
// with the CloseConnection flag, so the reader will deal with the connection; we
// still need something in the "finally" to ensure that broken SQL still results
// in the connection closing itself
return result;
}
catch
{
if (reader != null)
{
if (!reader.IsClosed) try { cmd.Cancel(); }
catch { /* don't spoil the existing exception */ }
reader.Dispose();
}
if (cmd != null) cmd.Dispose();
if (wasClosed) cnn.Close();
throw;
}
}
/// <summary>
/// Return a typed list of objects, reader is closed after the call
/// </summary>
private static IEnumerable<T> QueryInternal<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType)
{
var identity = new Identity(sql, commandType, cnn, typeof(T), param == null ? null : param.GetType(), null);
var info = GetCacheInfo(identity);
IDbCommand cmd = null;
IDataReader reader = null;
bool wasClosed = cnn.State == ConnectionState.Closed;
try
{
cmd = SetupCommand(cnn, transaction, sql, info.ParamReader, param, commandTimeout, commandType);
if (wasClosed) cnn.Open();
reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);
wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
// with the CloseConnection flag, so the reader will deal with the connection; we
// still need something in the "finally" to ensure that broken SQL still results
// in the connection closing itself
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(typeof(T), reader, 0, -1, false));
SetQueryCache(identity, info);
}
var func = tuple.Func;
while (reader.Read())
{
yield return (T)func(reader);
}
// happy path; close the reader cleanly - no
// need for "Cancel" etc
reader.Dispose();
reader = null;
}
finally
{
if (reader != null)
{
if (!reader.IsClosed) try { cmd.Cancel(); }
catch { /* don't spoil the existing exception */ }
reader.Dispose();
}
if (wasClosed) cnn.Close();
if (cmd != null) cmd.Dispose();
}
}
/// <summary>
/// Maps a query to objects
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset</typeparam>
/// <typeparam name="TSecond">The second type in the recordset</typeparam>
/// <typeparam name="TReturn">The return type</typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout</param>
/// <param name="commandType">Is it a stored proc or a batch?</param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(
#if CSHARP30
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
return MultiMap<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Maps a query to objects
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout</param>
/// <param name="commandType"></param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(
#if CSHARP30
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
return MultiMap<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 4 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(
#if CSHARP30
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
#endif
)
{
return MultiMap<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
#if !CSHARP30
/// <summary>
/// Perform a multi mapping query with 5 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
)
{
return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 6 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TSixth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
)
{
return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 7 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TSixth"></typeparam>
/// <typeparam name="TSeventh"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
#endif
partial class DontMap { }
static IEnumerable<TReturn> MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(
this IDbConnection cnn, string sql, object map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType)
{
var results = MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param, transaction, splitOn, commandTimeout, commandType, null, null);
return buffered ? results.ToList() : results;
}
static IEnumerable<TReturn> MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, object map, object param, IDbTransaction transaction, string splitOn, int? commandTimeout, CommandType? commandType, IDataReader reader, Identity identity)
{
identity = identity ?? new Identity(sql, commandType, cnn, typeof(TFirst), (object)param == null ? null : ((object)param).GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) });
CacheInfo cinfo = GetCacheInfo(identity);
IDbCommand ownedCommand = null;
IDataReader ownedReader = null;
bool wasClosed = cnn != null && cnn.State == ConnectionState.Closed;
try
{
if (reader == null)
{
ownedCommand = SetupCommand(cnn, transaction, sql, cinfo.ParamReader, (object)param, commandTimeout, commandType);
if (wasClosed) cnn.Open();
ownedReader = ownedCommand.ExecuteReader();
reader = ownedReader;
}
DeserializerState deserializer = default(DeserializerState);
Func<IDataReader, object>[] otherDeserializers = null;
int hash = GetColumnHash(reader);
if ((deserializer = cinfo.Deserializer).Func == null || (otherDeserializers = cinfo.OtherDeserializers) == null || hash != deserializer.Hash)
{
var deserializers = GenerateDeserializers(new Type[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) }, splitOn, reader);
deserializer = cinfo.Deserializer = new DeserializerState(hash, deserializers[0]);
otherDeserializers = cinfo.OtherDeserializers = deserializers.Skip(1).ToArray();
SetQueryCache(identity, cinfo);
}
Func<IDataReader, TReturn> mapIt = GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(deserializer.Func, otherDeserializers, map);
if (mapIt != null)
{
while (reader.Read())
{
yield return mapIt(reader);
}
}
}
finally
{
try
{
if (ownedReader != null)
{
ownedReader.Dispose();
}
}
finally
{
if (ownedCommand != null)
{
ownedCommand.Dispose();
}
if (wasClosed) cnn.Close();
}
}
}
private static Func<IDataReader, TReturn> GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(Func<IDataReader, object> deserializer, Func<IDataReader, object>[] otherDeserializers, object map)
{
switch (otherDeserializers.Length)
{
case 1:
return r => ((Func<TFirst, TSecond, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r));
case 2:
return r => ((Func<TFirst, TSecond, TThird, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r));
case 3:
return r => ((Func<TFirst, TSecond, TThird, TFourth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r));
#if !CSHARP30
case 4:
return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r));
case 5:
return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r), (TSixth)otherDeserializers[4](r));
case 6:
return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r), (TSixth)otherDeserializers[4](r), (TSeventh)otherDeserializers[5](r));
#endif
default:
throw new NotSupportedException();
}
}
private static Func<IDataReader, object>[] GenerateDeserializers(Type[] types, string splitOn, IDataReader reader)
{
int current = 0;
var splits = splitOn.Split(',').ToArray();
var splitIndex = 0;
Func<Type, int> nextSplit = type =>
{
var currentSplit = splits[splitIndex].Trim();
if (splits.Length > splitIndex + 1)
{
splitIndex++;
}
bool skipFirst = false;
int startingPos = current + 1;
// if our current type has the split, skip the first time you see it.
if (type != typeof(Object))
{
var props = DefaultTypeMap.GetSettableProps(type);
var fields = DefaultTypeMap.GetSettableFields(type);
foreach (var name in props.Select(p => p.Name).Concat(fields.Select(f => f.Name)))
{
if (string.Equals(name, currentSplit, StringComparison.OrdinalIgnoreCase))
{
skipFirst = true;
startingPos = current;
break;
}
}
}
int pos;
for (pos = startingPos; pos < reader.FieldCount; pos++)
{
// some people like ID some id ... assuming case insensitive splits for now
if (splitOn == "*")
{
break;
}
if (string.Equals(reader.GetName(pos), currentSplit, StringComparison.OrdinalIgnoreCase))
{
if (skipFirst)
{
skipFirst = false;
}
else
{
break;
}
}
}
current = pos;
return pos;
};
var deserializers = new List<Func<IDataReader, object>>();
int split = 0;
bool first = true;
foreach (var type in types)
{
if (type != typeof(DontMap))
{
int next = nextSplit(type);
deserializers.Add(GetDeserializer(type, reader, split, next - split, /* returnNullIfFirstMissing: */ !first));
first = false;
split = next;
}
}
return deserializers.ToArray();
}
private static CacheInfo GetCacheInfo(Identity identity)
{
CacheInfo info;
if (!TryGetQueryCache(identity, out info))
{
info = new CacheInfo();
if (identity.parametersType != null)
{
if (typeof(IDynamicParameters).IsAssignableFrom(identity.parametersType))
{
info.ParamReader = (cmd, obj) => { (obj as IDynamicParameters).AddParameters(cmd, identity); };
}
#if !CSHARP30
else if (typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(identity.parametersType) && typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(identity.parametersType))
{
info.ParamReader = (cmd, obj) =>
{
IDynamicParameters mapped = new DynamicParameters(obj);
mapped.AddParameters(cmd, identity);
};
}
#endif
else
{
info.ParamReader = CreateParamInfoGenerator(identity, false);
}
}
SetQueryCache(identity, info);
}
return info;
}
private static Func<IDataReader, object> GetDeserializer(Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing)
{
#if !CSHARP30
// dynamic is passed in as Object ... by c# design
if (type == typeof(object)
|| type == typeof(DapperRow))
{
return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing);
}
#else
if(type.IsAssignableFrom(typeof(Dictionary<string,object>)))
{
return GetDictionaryDeserializer(reader, startBound, length, returnNullIfFirstMissing);
}
#endif
Type underlyingType = null;
if (!(typeMap.ContainsKey(type) || type.IsEnum || type.FullName == LinqBinary ||
(type.IsValueType && (underlyingType = Nullable.GetUnderlyingType(type)) != null && underlyingType.IsEnum)))
{
return GetTypeDeserializer(type, reader, startBound, length, returnNullIfFirstMissing);
}
return GetStructDeserializer(type, underlyingType ?? type, startBound);
}
#if !CSHARP30
private sealed partial class DapperTable
{
string[] fieldNames;
readonly Dictionary<string, int> fieldNameLookup;
internal string[] FieldNames { get { return fieldNames; } }
public DapperTable(string[] fieldNames)
{
if (fieldNames == null) throw new ArgumentNullException("fieldNames");
this.fieldNames = fieldNames;
fieldNameLookup = new Dictionary<string, int>(fieldNames.Length, StringComparer.Ordinal);
// if there are dups, we want the **first** key to be the "winner" - so iterate backwards
for (int i = fieldNames.Length - 1; i >= 0; i--)
{
string key = fieldNames[i];
if (key != null) fieldNameLookup[key] = i;
}
}
internal int IndexOfName(string name)
{
int result;
return (name != null && fieldNameLookup.TryGetValue(name, out result)) ? result : -1;
}
internal int AddField(string name)
{
if (name == null) throw new ArgumentNullException("name");
if (fieldNameLookup.ContainsKey(name)) throw new InvalidOperationException("Field already exists: " + name);
int oldLen = fieldNames.Length;
Array.Resize(ref fieldNames, oldLen + 1); // yes, this is sub-optimal, but this is not the expected common case
fieldNames[oldLen] = name;
fieldNameLookup[name] = oldLen;
return oldLen;
}
internal bool FieldExists(string key)
{
return key != null && fieldNameLookup.ContainsKey(key);
}
public int FieldCount { get { return fieldNames.Length; } }
}
sealed partial class DapperRowMetaObject : System.Dynamic.DynamicMetaObject
{
static readonly MethodInfo getValueMethod = typeof(IDictionary<string, object>).GetProperty("Item").GetGetMethod();
static readonly MethodInfo setValueMethod = typeof(DapperRow).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) });
public DapperRowMetaObject(
System.Linq.Expressions.Expression expression,
System.Dynamic.BindingRestrictions restrictions
)
: base(expression, restrictions)
{
}
public DapperRowMetaObject(
System.Linq.Expressions.Expression expression,
System.Dynamic.BindingRestrictions restrictions,
object value
)
: base(expression, restrictions, value)
{
}
System.Dynamic.DynamicMetaObject CallMethod(
MethodInfo method,
System.Linq.Expressions.Expression[] parameters
)
{
var callMethod = new System.Dynamic.DynamicMetaObject(
System.Linq.Expressions.Expression.Call(
System.Linq.Expressions.Expression.Convert(Expression, LimitType),
method,
parameters),
System.Dynamic.BindingRestrictions.GetTypeRestriction(Expression, LimitType)
);
return callMethod;
}
public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder)
{
var parameters = new System.Linq.Expressions.Expression[]
{
System.Linq.Expressions.Expression.Constant(binder.Name)
};
var callMethod = CallMethod(getValueMethod, parameters);
return callMethod;
}
// Needed for Visual basic dynamic support
public override System.Dynamic.DynamicMetaObject BindInvokeMember(System.Dynamic.InvokeMemberBinder binder, System.Dynamic.DynamicMetaObject[] args)
{
var parameters = new System.Linq.Expressions.Expression[]
{
System.Linq.Expressions.Expression.Constant(binder.Name)
};
var callMethod = CallMethod(getValueMethod, parameters);
return callMethod;
}
public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value)
{
var parameters = new System.Linq.Expressions.Expression[]
{
System.Linq.Expressions.Expression.Constant(binder.Name),
value.Expression,
};
var callMethod = CallMethod(setValueMethod, parameters);
return callMethod;
}
}
private sealed partial class DapperRow
: System.Dynamic.IDynamicMetaObjectProvider
, IDictionary<string, object>
{
readonly DapperTable table;
object[] values;
public DapperRow(DapperTable table, object[] values)
{
if (table == null) throw new ArgumentNullException("table");
if (values == null) throw new ArgumentNullException("values");
this.table = table;
this.values = values;
}
private sealed class DeadValue
{
public static readonly DeadValue Default = new DeadValue();
private DeadValue() { }
}
int ICollection<KeyValuePair<string, object>>.Count
{
get
{
int count = 0;
for (int i = 0; i < values.Length; i++)
{
if (!(values[i] is DeadValue)) count++;
}
return count;
}
}
public bool TryGetValue(string name, out object value)
{
var index = table.IndexOfName(name);
if (index < 0)
{ // doesn't exist
value = null;
return false;
}
// exists, **even if** we don't have a value; consider table rows heterogeneous
value = index < values.Length ? values[index] : null;
if (value is DeadValue)
{ // pretend it isn't here
value = null;
return false;
}
return true;
}
public override string ToString()
{
var sb = new StringBuilder("{DapperRow");
foreach (var kv in this)
{
var value = kv.Value;
sb.Append(", ").Append(kv.Key);
if (value != null)
{
sb.Append(" = '").Append(kv.Value).Append('\'');
}
else
{
sb.Append(" = NULL");
}
}
return sb.Append('}').ToString();
}
System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(
System.Linq.Expressions.Expression parameter)
{
return new DapperRowMetaObject(parameter, System.Dynamic.BindingRestrictions.Empty, this);
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
var names = table.FieldNames;
for (var i = 0; i < names.Length; i++)
{
object value = i < values.Length ? values[i] : null;
if (!(value is DeadValue))
{
yield return new KeyValuePair<string, object>(names[i], value);
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#region Implementation of ICollection<KeyValuePair<string,object>>
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
IDictionary<string, object> dic = this;
dic.Add(item.Key, item.Value);
}
void ICollection<KeyValuePair<string, object>>.Clear()
{ // removes values for **this row**, but doesn't change the fundamental table
for (int i = 0; i < values.Length; i++)
values[i] = DeadValue.Default;
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
object value;
return TryGetValue(item.Key, out value) && Equals(value, item.Value);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
foreach (var kv in this)
{
array[arrayIndex++] = kv; // if they didn't leave enough space; not our fault
}
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
IDictionary<string, object> dic = this;
return dic.Remove(item.Key);
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{
get { return false; }
}
#endregion
#region Implementation of IDictionary<string,object>
bool IDictionary<string, object>.ContainsKey(string key)
{
int index = table.IndexOfName(key);
if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
return true;
}
void IDictionary<string, object>.Add(string key, object value)
{
SetValue(key, value, true);
}
bool IDictionary<string, object>.Remove(string key)
{
int index = table.IndexOfName(key);
if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
values[index] = DeadValue.Default;
return true;
}
object IDictionary<string, object>.this[string key]
{
get { object val; TryGetValue(key, out val); return val; }
set { SetValue(key, value, false); }
}
public object SetValue(string key, object value)
{
return SetValue(key, value, false);
}
private object SetValue(string key, object value, bool isAdd)
{
if (key == null) throw new ArgumentNullException("key");
int index = table.IndexOfName(key);
if (index < 0)
{
index = table.AddField(key);
}
else if (isAdd && index < values.Length && !(values[index] is DeadValue))
{
// then semantically, this value already exists
throw new ArgumentException("An item with the same key has already been added", "key");
}
int oldLength = values.Length;
if (oldLength <= index)
{
// we'll assume they're doing lots of things, and
// grow it to the full width of the table
Array.Resize(ref values, table.FieldCount);
for (int i = oldLength; i < values.Length; i++)
{
values[i] = DeadValue.Default;
}
}
return values[index] = value;
}
ICollection<string> IDictionary<string, object>.Keys
{
get { return this.Select(kv => kv.Key).ToArray(); }
}
ICollection<object> IDictionary<string, object>.Values
{
get { return this.Select(kv => kv.Value).ToArray(); }
}
#endregion
}
#endif
#if !CSHARP30
internal static Func<IDataReader, object> GetDapperRowDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
{
var fieldCount = reader.FieldCount;
if (length == -1)
{
length = fieldCount - startBound;
}
if (fieldCount <= startBound)
{
throw new ArgumentException("When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id", "splitOn");
}
var effectiveFieldCount = Math.Min(fieldCount - startBound, length);
DapperTable table = null;
return
r =>
{
if (table == null)
{
string[] names = new string[effectiveFieldCount];
for (int i = 0; i < effectiveFieldCount; i++)
{
names[i] = r.GetName(i + startBound);
}
table = new DapperTable(names);
}
var values = new object[effectiveFieldCount];
if (returnNullIfFirstMissing)
{
values[0] = r.GetValue(startBound);
if (values[0] is DBNull)
{
return null;
}
}
if (startBound == 0)
{
r.GetValues(values);
for (int i = 0; i < values.Length; i++)
if (values[i] is DBNull) values[i] = null;
}
else
{
var begin = returnNullIfFirstMissing ? 1 : 0;
for (var iter = begin; iter < effectiveFieldCount; ++iter)
{
object obj = r.GetValue(iter + startBound);
values[iter] = obj is DBNull ? null : obj;
}
}
return new DapperRow(table, values);
};
}
#else
internal static Func<IDataReader, object> GetDictionaryDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
{
var fieldCount = reader.FieldCount;
if (length == -1)
{
length = fieldCount - startBound;
}
if (fieldCount <= startBound)
{
throw new ArgumentException("When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id", "splitOn");
}
return
r =>
{
IDictionary<string, object> row = new Dictionary<string, object>(length);
for (var i = startBound; i < startBound + length; i++)
{
var tmp = r.GetValue(i);
tmp = tmp == DBNull.Value ? null : tmp;
row[r.GetName(i)] = tmp;
if (returnNullIfFirstMissing && i == startBound && tmp == null)
{
return null;
}
}
return row;
};
}
#endif
/// <summary>
/// Internal use only
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is for internal usage only", false)]
public static char ReadChar(object value)
{
if (value == null || value is DBNull) throw new ArgumentNullException("value");
string s = value as string;
if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", "value");
return s[0];
}
/// <summary>
/// Internal use only
/// </summary>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is for internal usage only", false)]
public static char? ReadNullableChar(object value)
{
if (value == null || value is DBNull) return null;
string s = value as string;
if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", "value");
return s[0];
}
/// <summary>
/// Internal use only
/// </summary>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is for internal usage only", true)]
public static IDbDataParameter FindOrAddParameter(IDataParameterCollection parameters, IDbCommand command, string name)
{
IDbDataParameter result;
if (parameters.Contains(name))
{
result = (IDbDataParameter)parameters[name];
}
else
{
result = command.CreateParameter();
result.ParameterName = name;
parameters.Add(result);
}
return result;
}
/// <summary>
/// Internal use only
/// </summary>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is for internal usage only", false)]
public static void PackListParameters(IDbCommand command, string namePrefix, object value)
{
// initially we tried TVP, however it performs quite poorly.
// keep in mind SQL support up to 2000 params easily in sp_executesql, needing more is rare
var list = value as IEnumerable;
var count = 0;
if (list != null)
{
if (FeatureSupport.Get(command.Connection).Arrays)
{
var arrayParm = command.CreateParameter();
arrayParm.Value = list;
arrayParm.ParameterName = namePrefix;
command.Parameters.Add(arrayParm);
}
else
{
bool isString = value is IEnumerable<string>;
bool isDbString = value is IEnumerable<DbString>;
foreach (var item in list)
{
count++;
var listParam = command.CreateParameter();
listParam.ParameterName = namePrefix + count;
listParam.Value = item ?? DBNull.Value;
if (isString)
{
listParam.Size = 4000;
if (item != null && ((string)item).Length > 4000)
{
listParam.Size = -1;
}
}
if (isDbString && item as DbString != null)
{
var str = item as DbString;
str.AddParameter(command, listParam.ParameterName);
}
else
{
command.Parameters.Add(listParam);
}
}
if (count == 0)
{
command.CommandText = Regex.Replace(command.CommandText, @"[?@:]" + Regex.Escape(namePrefix), "(SELECT NULL WHERE 1 = 0)");
}
else
{
command.CommandText = Regex.Replace(command.CommandText, @"[?@:]" + Regex.Escape(namePrefix), match =>
{
var grp = match.Value;
var sb = new StringBuilder("(").Append(grp).Append(1);
for (int i = 2; i <= count; i++)
{
sb.Append(',').Append(grp).Append(i);
}
return sb.Append(')').ToString();
});
}
}
}
}
private static IEnumerable<PropertyInfo> FilterParameters(IEnumerable<PropertyInfo> parameters, string sql)
{
return parameters.Where(p => Regex.IsMatch(sql, "[@:]" + p.Name + "([^a-zA-Z0-9_]+|$)", RegexOptions.IgnoreCase | RegexOptions.Multiline));
}
/// <summary>
/// Internal use only
/// </summary>
public static Action<IDbCommand, object> CreateParamInfoGenerator(Identity identity, bool checkForDuplicates)
{
Type type = identity.parametersType;
bool filterParams = identity.commandType.GetValueOrDefault(CommandType.Text) == CommandType.Text;
var dm = new DynamicMethod(string.Format("ParamInfo{0}", Guid.NewGuid()), null, new[] { typeof(IDbCommand), typeof(object) }, type, true);
var il = dm.GetILGenerator();
il.DeclareLocal(type); // 0
bool haveInt32Arg1 = false;
il.Emit(OpCodes.Ldarg_1); // stack is now [untyped-param]
il.Emit(OpCodes.Unbox_Any, type); // stack is now [typed-param]
il.Emit(OpCodes.Stloc_0);// stack is now empty
il.Emit(OpCodes.Ldarg_0); // stack is now [command]
il.EmitCall(OpCodes.Callvirt, typeof(IDbCommand).GetProperty("Parameters").GetGetMethod(), null); // stack is now [parameters]
IEnumerable<PropertyInfo> props = type.GetProperties().Where(p => p.GetIndexParameters().Length == 0).OrderBy(p => p.Name);
if (filterParams)
{
props = FilterParameters(props, identity.sql);
}
foreach (var prop in props)
{
if (filterParams)
{
if (identity.sql.IndexOf("@" + prop.Name, StringComparison.InvariantCultureIgnoreCase) < 0
&& identity.sql.IndexOf(":" + prop.Name, StringComparison.InvariantCultureIgnoreCase) < 0)
{ // can't see the parameter in the text (even in a comment, etc) - burn it with fire
continue;
}
}
if (typeof(ICustomQueryParameter).IsAssignableFrom(prop.PropertyType))
{
il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [typed-param]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [dbstring]
il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [dbstring] [command]
il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [dbstring] [command] [name]
il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("AddParameter"), null); // stack is now [parameters]
continue;
}
DbType dbType = LookupDbType(prop.PropertyType, prop.Name);
if (dbType == DynamicParameters.EnumerableMultiParameter)
{
// this actually represents special handling for list types;
il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [command]
il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [command] [name]
il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [command] [name] [typed-param]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [command] [name] [typed-value]
if (prop.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, prop.PropertyType); // stack is [parameters] [command] [name] [boxed-value]
}
il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("PackListParameters"), null); // stack is [parameters]
continue;
}
il.Emit(OpCodes.Dup); // stack is now [parameters] [parameters]
il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [parameters] [command]
if (checkForDuplicates)
{
// need to be a little careful about adding; use a utility method
il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [parameters] [command] [name]
il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("FindOrAddParameter"), null); // stack is [parameters] [parameter]
}
else
{
// no risk of duplicates; just blindly add
il.EmitCall(OpCodes.Callvirt, typeof(IDbCommand).GetMethod("CreateParameter"), null);// stack is now [parameters] [parameters] [parameter]
il.Emit(OpCodes.Dup);// stack is now [parameters] [parameters] [parameter] [parameter]
il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name]
il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("ParameterName").GetSetMethod(), null);// stack is now [parameters] [parameters] [parameter]
}
if (dbType != DbType.Time) // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time
{
il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
EmitInt32(il, (int)dbType);// stack is now [parameters] [[parameters]] [parameter] [parameter] [db-type]
il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("DbType").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
}
il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
EmitInt32(il, (int)ParameterDirection.Input);// stack is now [parameters] [[parameters]] [parameter] [parameter] [dir]
il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("Direction").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [[parameters]] [parameter] [parameter] [typed-param]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [[parameters]] [parameter] [parameter] [typed-value]
bool checkForNull = true;
if (prop.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, prop.PropertyType); // stack is [parameters] [[parameters]] [parameter] [parameter] [boxed-value]
if (Nullable.GetUnderlyingType(prop.PropertyType) == null)
{ // struct but not Nullable<T>; boxed value cannot be null
checkForNull = false;
}
}
if (checkForNull)
{
if (dbType == DbType.String && !haveInt32Arg1)
{
il.DeclareLocal(typeof(int));
haveInt32Arg1 = true;
}
// relative stack: [boxed value]
il.Emit(OpCodes.Dup);// relative stack: [boxed value] [boxed value]
Label notNull = il.DefineLabel();
Label? allDone = dbType == DbType.String ? il.DefineLabel() : (Label?)null;
il.Emit(OpCodes.Brtrue_S, notNull);
// relative stack [boxed value = null]
il.Emit(OpCodes.Pop); // relative stack empty
il.Emit(OpCodes.Ldsfld, typeof(DBNull).GetField("Value")); // relative stack [DBNull]
if (dbType == DbType.String)
{
EmitInt32(il, 0);
il.Emit(OpCodes.Stloc_1);
}
if (allDone != null) il.Emit(OpCodes.Br_S, allDone.Value);
il.MarkLabel(notNull);
if (prop.PropertyType == typeof(string))
{
il.Emit(OpCodes.Dup); // [string] [string]
il.EmitCall(OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(), null); // [string] [length]
EmitInt32(il, 4000); // [string] [length] [4000]
il.Emit(OpCodes.Cgt); // [string] [0 or 1]
Label isLong = il.DefineLabel(), lenDone = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, isLong);
EmitInt32(il, 4000); // [string] [4000]
il.Emit(OpCodes.Br_S, lenDone);
il.MarkLabel(isLong);
EmitInt32(il, -1); // [string] [-1]
il.MarkLabel(lenDone);
il.Emit(OpCodes.Stloc_1); // [string]
}
if (prop.PropertyType.FullName == LinqBinary)
{
il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("ToArray", BindingFlags.Public | BindingFlags.Instance), null);
}
if (allDone != null) il.MarkLabel(allDone.Value);
// relative stack [boxed value or DBNull]
}
il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("Value").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
if (prop.PropertyType == typeof(string))
{
var endOfSize = il.DefineLabel();
// don't set if 0
il.Emit(OpCodes.Ldloc_1); // [parameters] [[parameters]] [parameter] [size]
il.Emit(OpCodes.Brfalse_S, endOfSize); // [parameters] [[parameters]] [parameter]
il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
il.Emit(OpCodes.Ldloc_1); // stack is now [parameters] [[parameters]] [parameter] [parameter] [size]
il.EmitCall(OpCodes.Callvirt, typeof(IDbDataParameter).GetProperty("Size").GetSetMethod(), null); // stack is now [parameters] [[parameters]] [parameter]
il.MarkLabel(endOfSize);
}
if (checkForDuplicates)
{
// stack is now [parameters] [parameter]
il.Emit(OpCodes.Pop); // don't need parameter any more
}
else
{
// stack is now [parameters] [parameters] [parameter]
// blindly add
il.EmitCall(OpCodes.Callvirt, typeof(IList).GetMethod("Add"), null); // stack is now [parameters]
il.Emit(OpCodes.Pop); // IList.Add returns the new index (int); we don't care
}
}
// stack is currently [parameters]
il.Emit(OpCodes.Pop); // stack is now empty
il.Emit(OpCodes.Ret);
return (Action<IDbCommand, object>)dm.CreateDelegate(typeof(Action<IDbCommand, object>));
}
private static IDbCommand SetupCommand(IDbConnection cnn, IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout, CommandType? commandType)
{
var cmd = cnn.CreateCommand();
var bindByName = GetBindByName(cmd.GetType());
if (bindByName != null) bindByName(cmd, true);
if (transaction != null)
cmd.Transaction = transaction;
cmd.CommandText = sql;
if (commandTimeout.HasValue)
cmd.CommandTimeout = commandTimeout.Value;
if (commandType.HasValue)
cmd.CommandType = commandType.Value;
if (paramReader != null)
{
paramReader(cmd, obj);
}
return cmd;
}
private static int ExecuteCommand(IDbConnection cnn, IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout, CommandType? commandType)
{
IDbCommand cmd = null;
bool wasClosed = cnn.State == ConnectionState.Closed;
try
{
cmd = SetupCommand(cnn, transaction, sql, paramReader, obj, commandTimeout, commandType);
if (wasClosed) cnn.Open();
return cmd.ExecuteNonQuery();
}
finally
{
if (wasClosed) cnn.Close();
if (cmd != null) cmd.Dispose();
}
}
private static Func<IDataReader, object> GetStructDeserializer(Type type, Type effectiveType, int index)
{
// no point using special per-type handling here; it boils down to the same, plus not all are supported anyway (see: SqlDataReader.GetChar - not supported!)
#pragma warning disable 618
if (type == typeof(char))
{ // this *does* need special handling, though
return r => SqlMapper.ReadChar(r.GetValue(index));
}
if (type == typeof(char?))
{
return r => SqlMapper.ReadNullableChar(r.GetValue(index));
}
if (type.FullName == LinqBinary)
{
return r => Activator.CreateInstance(type, r.GetValue(index));
}
#pragma warning restore 618
if (effectiveType.IsEnum)
{ // assume the value is returned as the correct type (int/byte/etc), but box back to the typed enum
return r =>
{
var val = r.GetValue(index);
return val is DBNull ? null : Enum.ToObject(effectiveType, val);
};
}
return r =>
{
var val = r.GetValue(index);
return val is DBNull ? null : val;
};
}
static readonly MethodInfo
enumParse = typeof(Enum).GetMethod("Parse", new Type[] { typeof(Type), typeof(string), typeof(bool) }),
getItem = typeof(IDataRecord).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.GetIndexParameters().Any() && p.GetIndexParameters()[0].ParameterType == typeof(int))
.Select(p => p.GetGetMethod()).First();
/// <summary>
/// Gets type-map for the given type
/// </summary>
/// <returns>Type map implementation, DefaultTypeMap instance if no override present</returns>
public static ITypeMap GetTypeMap(Type type)
{
if (type == null) throw new ArgumentNullException("type");
var map = (ITypeMap)_typeMaps[type];
if (map == null)
{
lock (_typeMaps)
{ // double-checked; store this to avoid reflection next time we see this type
// since multiple queries commonly use the same domain-entity/DTO/view-model type
map = (ITypeMap)_typeMaps[type];
if (map == null)
{
map = new DefaultTypeMap(type);
_typeMaps[type] = map;
}
}
}
return map;
}
// use Hashtable to get free lockless reading
private static readonly Hashtable _typeMaps = new Hashtable();
/// <summary>
/// Set custom mapping for type deserializers
/// </summary>
/// <param name="type">Entity type to override</param>
/// <param name="map">Mapping rules impementation, null to remove custom map</param>
public static void SetTypeMap(Type type, ITypeMap map)
{
if (type == null)
throw new ArgumentNullException("type");
if (map == null || map is DefaultTypeMap)
{
lock (_typeMaps)
{
_typeMaps.Remove(type);
}
}
else
{
lock (_typeMaps)
{
_typeMaps[type] = map;
}
}
PurgeQueryCacheByType(type);
}
/// <summary>
/// Internal use only
/// </summary>
/// <param name="type"></param>
/// <param name="reader"></param>
/// <param name="startBound"></param>
/// <param name="length"></param>
/// <param name="returnNullIfFirstMissing"></param>
/// <returns></returns>
public static Func<IDataReader, object> GetTypeDeserializer(
#if CSHARP30
Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing
#else
Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false
#endif
)
{
var dm = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(object), new[] { typeof(IDataReader) }, true);
var il = dm.GetILGenerator();
il.DeclareLocal(typeof(int));
il.DeclareLocal(type);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Stloc_0);
if (length == -1)
{
length = reader.FieldCount - startBound;
}
if (reader.FieldCount <= startBound)
{
throw new ArgumentException("When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id", "splitOn");
}
var names = Enumerable.Range(startBound, length).Select(i => reader.GetName(i)).ToArray();
ITypeMap typeMap = GetTypeMap(type);
int index = startBound;
ConstructorInfo specializedConstructor = null;
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca_S, (byte)1);
il.Emit(OpCodes.Initobj, type);
}
else
{
var types = new Type[length];
for (int i = startBound; i < startBound + length; i++)
{
types[i - startBound] = reader.GetFieldType(i);
}
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca_S, (byte)1);
il.Emit(OpCodes.Initobj, type);
}
else
{
var ctor = typeMap.FindConstructor(names, types);
if (ctor == null)
{
string proposedTypes = "(" + String.Join(", ", types.Select((t, i) => t.FullName + " " + names[i]).ToArray()) + ")";
throw new InvalidOperationException(String.Format("A parameterless default constructor or one matching signature {0} is required for {1} materialization", proposedTypes, type.FullName));
}
if (ctor.GetParameters().Length == 0)
{
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_1);
}
else
specializedConstructor = ctor;
}
}
il.BeginExceptionBlock();
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca_S, (byte)1);// [target]
}
else if (specializedConstructor == null)
{
il.Emit(OpCodes.Ldloc_1);// [target]
}
var members = (specializedConstructor != null
? names.Select(n => typeMap.GetConstructorParameter(specializedConstructor, n))
: names.Select(n => typeMap.GetMember(n))).ToList();
// stack is now [target]
bool first = true;
var allDone = il.DefineLabel();
int enumDeclareLocal = -1;
foreach (var item in members)
{
if (item != null)
{
if (specializedConstructor == null)
il.Emit(OpCodes.Dup); // stack is now [target][target]
Label isDbNullLabel = il.DefineLabel();
Label finishLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0); // stack is now [target][target][reader]
EmitInt32(il, index); // stack is now [target][target][reader][index]
il.Emit(OpCodes.Dup);// stack is now [target][target][reader][index][index]
il.Emit(OpCodes.Stloc_0);// stack is now [target][target][reader][index]
il.Emit(OpCodes.Callvirt, getItem); // stack is now [target][target][value-as-object]
Type memberType = item.MemberType;
if (memberType == typeof(char) || memberType == typeof(char?))
{
il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod(
memberType == typeof(char) ? "ReadChar" : "ReadNullableChar", BindingFlags.Static | BindingFlags.Public), null); // stack is now [target][target][typed-value]
}
else
{
il.Emit(OpCodes.Dup); // stack is now [target][target][value][value]
il.Emit(OpCodes.Isinst, typeof(DBNull)); // stack is now [target][target][value-as-object][DBNull or null]
il.Emit(OpCodes.Brtrue_S, isDbNullLabel); // stack is now [target][target][value-as-object]
// unbox nullable enums as the primitive, i.e. byte etc
var nullUnderlyingType = Nullable.GetUnderlyingType(memberType);
var unboxType = nullUnderlyingType != null && nullUnderlyingType.IsEnum ? nullUnderlyingType : memberType;
if (unboxType.IsEnum)
{
if (enumDeclareLocal == -1)
{
enumDeclareLocal = il.DeclareLocal(typeof(string)).LocalIndex;
}
Label isNotString = il.DefineLabel();
il.Emit(OpCodes.Dup); // stack is now [target][target][value][value]
il.Emit(OpCodes.Isinst, typeof(string)); // stack is now [target][target][value-as-object][string or null]
il.Emit(OpCodes.Dup);// stack is now [target][target][value-as-object][string or null][string or null]
StoreLocal(il, enumDeclareLocal); // stack is now [target][target][value-as-object][string or null]
il.Emit(OpCodes.Brfalse_S, isNotString); // stack is now [target][target][value-as-object]
il.Emit(OpCodes.Pop); // stack is now [target][target]
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][enum-type-token]
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);// stack is now [target][target][enum-type]
il.Emit(OpCodes.Ldloc_2); // stack is now [target][target][enum-type][string]
il.Emit(OpCodes.Ldc_I4_1); // stack is now [target][target][enum-type][string][true]
il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [target][target][enum-as-object]
il.MarkLabel(isNotString);
il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
if (nullUnderlyingType != null)
{
il.Emit(OpCodes.Newobj, memberType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][enum-value]
}
}
else if (memberType.FullName == LinqBinary)
{
il.Emit(OpCodes.Unbox_Any, typeof(byte[])); // stack is now [target][target][byte-array]
il.Emit(OpCodes.Newobj, memberType.GetConstructor(new Type[] { typeof(byte[]) }));// stack is now [target][target][binary]
}
else
{
Type dataType = reader.GetFieldType(index);
TypeCode dataTypeCode = Type.GetTypeCode(dataType), unboxTypeCode = Type.GetTypeCode(unboxType);
if (dataType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == Type.GetTypeCode(nullUnderlyingType))
{
il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
}
else
{
// not a direct match; need to tweak the unbox
bool handled = true;
OpCode opCode = default(OpCode);
if (dataTypeCode == TypeCode.Decimal || unboxTypeCode == TypeCode.Decimal)
{ // no IL level conversions to/from decimal; I guess we could use the static operators, but
// this feels an edge-case
handled = false;
}
else
{
switch (unboxTypeCode)
{
case TypeCode.Byte:
opCode = OpCodes.Conv_Ovf_I1_Un; break;
case TypeCode.SByte:
opCode = OpCodes.Conv_Ovf_I1; break;
case TypeCode.UInt16:
opCode = OpCodes.Conv_Ovf_I2_Un; break;
case TypeCode.Int16:
opCode = OpCodes.Conv_Ovf_I2; break;
case TypeCode.UInt32:
opCode = OpCodes.Conv_Ovf_I4_Un; break;
case TypeCode.Boolean: // boolean is basically an int, at least at this level
case TypeCode.Int32:
opCode = OpCodes.Conv_Ovf_I4; break;
case TypeCode.UInt64:
opCode = OpCodes.Conv_Ovf_I8_Un; break;
case TypeCode.Int64:
opCode = OpCodes.Conv_Ovf_I8; break;
case TypeCode.Single:
opCode = OpCodes.Conv_R4; break;
case TypeCode.Double:
opCode = OpCodes.Conv_R8; break;
default:
handled = false;
break;
}
}
if (handled)
{ // unbox as the data-type, then use IL-level convert
il.Emit(OpCodes.Unbox_Any, dataType); // stack is now [target][target][data-typed-value]
il.Emit(opCode); // stack is now [target][target][typed-value]
if (unboxTypeCode == TypeCode.Boolean)
{ // compare to zero; I checked "csc" - this is the trick it uses; nice
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
}
}
else
{ // use flexible conversion
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][value][member-type-token]
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); // stack is now [target][target][value][member-type]
il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
}
}
}
}
if (specializedConstructor == null)
{
// Store the value in the property/field
if (item.Property != null)
{
if (type.IsValueType)
{
il.Emit(OpCodes.Call, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
}
else
{
il.Emit(OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
}
}
else
{
il.Emit(OpCodes.Stfld, item.Field); // stack is now [target]
}
}
il.Emit(OpCodes.Br_S, finishLabel); // stack is now [target]
il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value]
if (specializedConstructor != null)
{
il.Emit(OpCodes.Pop);
if (item.MemberType.IsValueType)
{
int localIndex = il.DeclareLocal(item.MemberType).LocalIndex;
LoadLocalAddress(il, localIndex);
il.Emit(OpCodes.Initobj, item.MemberType);
LoadLocal(il, localIndex);
}
else
{
il.Emit(OpCodes.Ldnull);
}
}
else
{
il.Emit(OpCodes.Pop); // stack is now [target][target]
il.Emit(OpCodes.Pop); // stack is now [target]
}
if (first && returnNullIfFirstMissing)
{
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldnull); // stack is now [null]
il.Emit(OpCodes.Stloc_1);
il.Emit(OpCodes.Br, allDone);
}
il.MarkLabel(finishLabel);
}
first = false;
index += 1;
}
if (type.IsValueType)
{
il.Emit(OpCodes.Pop);
}
else
{
if (specializedConstructor != null)
{
il.Emit(OpCodes.Newobj, specializedConstructor);
}
il.Emit(OpCodes.Stloc_1); // stack is empty
}
il.MarkLabel(allDone);
il.BeginCatchBlock(typeof(Exception)); // stack is Exception
il.Emit(OpCodes.Ldloc_0); // stack is Exception, index
il.Emit(OpCodes.Ldarg_0); // stack is Exception, index, reader
il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("ThrowDataException"), null);
il.EndExceptionBlock();
il.Emit(OpCodes.Ldloc_1); // stack is [rval]
if (type.IsValueType)
{
il.Emit(OpCodes.Box, type);
}
il.Emit(OpCodes.Ret);
return (Func<IDataReader, object>)dm.CreateDelegate(typeof(Func<IDataReader, object>));
}
private static void LoadLocal(ILGenerator il, int index)
{
if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
switch (index)
{
case 0: il.Emit(OpCodes.Ldloc_0); break;
case 1: il.Emit(OpCodes.Ldloc_1); break;
case 2: il.Emit(OpCodes.Ldloc_2); break;
case 3: il.Emit(OpCodes.Ldloc_3); break;
default:
if (index <= 255)
{
il.Emit(OpCodes.Ldloc_S, (byte)index);
}
else
{
il.Emit(OpCodes.Ldloc, (short)index);
}
break;
}
}
private static void StoreLocal(ILGenerator il, int index)
{
if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
switch (index)
{
case 0: il.Emit(OpCodes.Stloc_0); break;
case 1: il.Emit(OpCodes.Stloc_1); break;
case 2: il.Emit(OpCodes.Stloc_2); break;
case 3: il.Emit(OpCodes.Stloc_3); break;
default:
if (index <= 255)
{
il.Emit(OpCodes.Stloc_S, (byte)index);
}
else
{
il.Emit(OpCodes.Stloc, (short)index);
}
break;
}
}
private static void LoadLocalAddress(ILGenerator il, int index)
{
if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
if (index <= 255)
{
il.Emit(OpCodes.Ldloca_S, (byte)index);
}
else
{
il.Emit(OpCodes.Ldloca, (short)index);
}
}
/// <summary>
/// Throws a data exception, only used internally
/// </summary>
/// <param name="ex"></param>
/// <param name="index"></param>
/// <param name="reader"></param>
public static void ThrowDataException(Exception ex, int index, IDataReader reader)
{
Exception toThrow;
try
{
string name = "(n/a)", value = "(n/a)";
if (reader != null && index >= 0 && index < reader.FieldCount)
{
name = reader.GetName(index);
object val = reader.GetValue(index);
if (val == null || val is DBNull)
{
value = "<null>";
}
else
{
value = Convert.ToString(val) + " - " + Type.GetTypeCode(val.GetType());
}
}
toThrow = new DataException(string.Format("Error parsing column {0} ({1}={2})", index, name, value), ex);
}
catch
{ // throw the **original** exception, wrapped as DataException
toThrow = new DataException(ex.Message, ex);
}
throw toThrow;
}
private static void EmitInt32(ILGenerator il, int value)
{
switch (value)
{
case -1: il.Emit(OpCodes.Ldc_I4_M1); break;
case 0: il.Emit(OpCodes.Ldc_I4_0); break;
case 1: il.Emit(OpCodes.Ldc_I4_1); break;
case 2: il.Emit(OpCodes.Ldc_I4_2); break;
case 3: il.Emit(OpCodes.Ldc_I4_3); break;
case 4: il.Emit(OpCodes.Ldc_I4_4); break;
case 5: il.Emit(OpCodes.Ldc_I4_5); break;
case 6: il.Emit(OpCodes.Ldc_I4_6); break;
case 7: il.Emit(OpCodes.Ldc_I4_7); break;
case 8: il.Emit(OpCodes.Ldc_I4_8); break;
default:
if (value >= -128 && value <= 127)
{
il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
}
else
{
il.Emit(OpCodes.Ldc_I4, value);
}
break;
}
}
/// <summary>
/// How should connection strings be compared for equivalence? Defaults to StringComparer.Ordinal.
/// Providing a custom implementation can be useful for allowing multi-tenancy databases with identical
/// schema to share startegies. Note that usual equivalence rules apply: any equivalent connection strings
/// <b>MUST</b> yield the same hash-code.
/// </summary>
public static IEqualityComparer<string> ConnectionStringComparer
{
get { return connectionStringComparer; }
set { connectionStringComparer = value ?? StringComparer.Ordinal; }
}
private static IEqualityComparer<string> connectionStringComparer = StringComparer.Ordinal;
/// <summary>
/// The grid reader provides interfaces for reading multiple result sets from a Dapper query
/// </summary>
public partial class GridReader : IDisposable
{
private IDataReader reader;
private IDbCommand command;
private Identity identity;
internal GridReader(IDbCommand command, IDataReader reader, Identity identity)
{
this.command = command;
this.reader = reader;
this.identity = identity;
}
#if !CSHARP30
/// <summary>
/// Read the next grid of results, returned as a dynamic object
/// </summary>
public IEnumerable<dynamic> Read(bool buffered = true)
{
return Read<DapperRow>(buffered);
}
#endif
#if CSHARP30
/// <summary>
/// Read the next grid of results
/// </summary>
public IEnumerable<T> Read<T>()
{
return Read<T>(true);
}
#endif
/// <summary>
/// Read the next grid of results
/// </summary>
#if CSHARP30
public IEnumerable<T> Read<T>(bool buffered)
#else
public IEnumerable<T> Read<T>(bool buffered = true)
#endif
{
if (reader == null) throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
if (consumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
var typedIdentity = identity.ForGrid(typeof(T), gridIndex);
CacheInfo cache = GetCacheInfo(typedIdentity);
var deserializer = cache.Deserializer;
int hash = GetColumnHash(reader);
if (deserializer.Func == null || deserializer.Hash != hash)
{
deserializer = new DeserializerState(hash, GetDeserializer(typeof(T), reader, 0, -1, false));
cache.Deserializer = deserializer;
}
consumed = true;
var result = ReadDeferred<T>(gridIndex, deserializer.Func, typedIdentity);
return buffered ? result.ToList() : result;
}
private IEnumerable<TReturn> MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(object func, string splitOn)
{
var identity = this.identity.ForGrid(typeof(TReturn), new Type[] {
typeof(TFirst),
typeof(TSecond),
typeof(TThird),
typeof(TFourth),
typeof(TFifth),
typeof(TSixth),
typeof(TSeventh)
}, gridIndex);
try
{
foreach (var r in SqlMapper.MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, null, func, null, null, splitOn, null, null, reader, identity))
{
yield return r;
}
}
finally
{
NextResult();
}
}
#if CSHARP30
/// <summary>
/// Read multiple objects from a single recordset on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn)
{
return Read<TFirst, TSecond, TReturn>(func, splitOn, true);
}
#endif
/// <summary>
/// Read multiple objects from a single recordset on the grid
/// </summary>
#if CSHARP30
public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn, bool buffered)
#else
public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn = "id", bool buffered = true)
#endif
{
var result = MultiReadInternal<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
#if CSHARP30
/// <summary>
/// Read multiple objects from a single recordset on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn)
{
return Read<TFirst, TSecond, TThird, TReturn>(func, splitOn, true);
}
#endif
/// <summary>
/// Read multiple objects from a single recordset on the grid
/// </summary>
#if CSHARP30
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn, bool buffered)
#else
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn = "id", bool buffered = true)
#endif
{
var result = MultiReadInternal<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
#if CSHARP30
/// <summary>
/// Read multiple objects from a single record set on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn)
{
return Read<TFirst, TSecond, TThird, TFourth, TReturn>(func, splitOn, true);
}
#endif
/// <summary>
/// Read multiple objects from a single record set on the grid
/// </summary>
#if CSHARP30
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn, bool buffered)
#else
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn = "id", bool buffered = true)
#endif
{
var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
#if !CSHARP30
/// <summary>
/// Read multiple objects from a single record set on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> func, string splitOn = "id", bool buffered = true)
{
var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
/// <summary>
/// Read multiple objects from a single record set on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> func, string splitOn = "id", bool buffered = true)
{
var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
/// <summary>
/// Read multiple objects from a single record set on the grid
/// </summary>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> func, string splitOn = "id", bool buffered = true)
{
var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(func, splitOn);
return buffered ? result.ToList() : result;
}
#endif
private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> deserializer, Identity typedIdentity)
{
try
{
while (index == gridIndex && reader.Read())
{
yield return (T)deserializer(reader);
}
}
finally // finally so that First etc progresses things even when multiple rows
{
if (index == gridIndex)
{
NextResult();
}
}
}
private int gridIndex, readCount;
private bool consumed;
private void NextResult()
{
if (reader.NextResult())
{
readCount++;
gridIndex++;
consumed = false;
}
else
{
// happy path; close the reader cleanly - no
// need for "Cancel" etc
reader.Dispose();
reader = null;
Dispose();
}
}
/// <summary>
/// Dispose the grid, closing and disposing both the underlying reader and command.
/// </summary>
public void Dispose()
{
if (reader != null)
{
if (!reader.IsClosed && command != null) command.Cancel();
reader.Dispose();
reader = null;
}
if (command != null)
{
command.Dispose();
command = null;
}
}
}
}
/// <summary>
/// A bag of parameters that can be passed to the Dapper Query and Execute methods
/// </summary>
partial class DynamicParameters : SqlMapper.IDynamicParameters
{
internal const DbType EnumerableMultiParameter = (DbType)(-1);
static Dictionary<SqlMapper.Identity, Action<IDbCommand, object>> paramReaderCache = new Dictionary<SqlMapper.Identity, Action<IDbCommand, object>>();
Dictionary<string, ParamInfo> parameters = new Dictionary<string, ParamInfo>();
List<object> templates;
partial class ParamInfo
{
public string Name { get; set; }
public object Value { get; set; }
public ParameterDirection ParameterDirection { get; set; }
public DbType? DbType { get; set; }
public int? Size { get; set; }
public IDbDataParameter AttachedParam { get; set; }
}
/// <summary>
/// construct a dynamic parameter bag
/// </summary>
public DynamicParameters() { }
/// <summary>
/// construct a dynamic parameter bag
/// </summary>
/// <param name="template">can be an anonymous type or a DynamicParameters bag</param>
public DynamicParameters(object template)
{
AddDynamicParams(template);
}
/// <summary>
/// Append a whole object full of params to the dynamic
/// EG: AddDynamicParams(new {A = 1, B = 2}) // will add property A and B to the dynamic
/// </summary>
/// <param name="param"></param>
public void AddDynamicParams(
#if CSHARP30
object param
#else
dynamic param
#endif
)
{
var obj = param as object;
if (obj != null)
{
var subDynamic = obj as DynamicParameters;
if (subDynamic == null)
{
var dictionary = obj as IEnumerable<KeyValuePair<string, object>>;
if (dictionary == null)
{
templates = templates ?? new List<object>();
templates.Add(obj);
}
else
{
foreach (var kvp in dictionary)
{
#if CSHARP30
Add(kvp.Key, kvp.Value, null, null, null);
#else
Add(kvp.Key, kvp.Value);
#endif
}
}
}
else
{
if (subDynamic.parameters != null)
{
foreach (var kvp in subDynamic.parameters)
{
parameters.Add(kvp.Key, kvp.Value);
}
}
if (subDynamic.templates != null)
{
templates = templates ?? new List<object>();
foreach (var t in subDynamic.templates)
{
templates.Add(t);
}
}
}
}
}
/// <summary>
/// Add a parameter to this dynamic parameter list
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="dbType"></param>
/// <param name="direction"></param>
/// <param name="size"></param>
public void Add(
#if CSHARP30
string name, object value, DbType? dbType, ParameterDirection? direction, int? size
#else
string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null
#endif
)
{
parameters[Clean(name)] = new ParamInfo() { Name = name, Value = value, ParameterDirection = direction ?? ParameterDirection.Input, DbType = dbType, Size = size };
}
static string Clean(string name)
{
if (!string.IsNullOrEmpty(name))
{
switch (name[0])
{
case '@':
case ':':
case '?':
return name.Substring(1);
}
}
return name;
}
void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
AddParameters(command, identity);
}
/// <summary>
/// Add all the parameters needed to the command just before it executes
/// </summary>
/// <param name="command">The raw command prior to execution</param>
/// <param name="identity">Information about the query</param>
protected void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
if (templates != null)
{
foreach (var template in templates)
{
var newIdent = identity.ForDynamicParameters(template.GetType());
Action<IDbCommand, object> appender;
lock (paramReaderCache)
{
if (!paramReaderCache.TryGetValue(newIdent, out appender))
{
appender = SqlMapper.CreateParamInfoGenerator(newIdent, true);
paramReaderCache[newIdent] = appender;
}
}
appender(command, template);
}
}
foreach (var param in parameters.Values)
{
var dbType = param.DbType;
var val = param.Value;
string name = Clean(param.Name);
if (dbType == null && val != null) dbType = SqlMapper.LookupDbType(val.GetType(), name);
if (dbType == DynamicParameters.EnumerableMultiParameter)
{
#pragma warning disable 612, 618
SqlMapper.PackListParameters(command, name, val);
#pragma warning restore 612, 618
}
else
{
bool add = !command.Parameters.Contains(name);
IDbDataParameter p;
if (add)
{
p = command.CreateParameter();
p.ParameterName = name;
}
else
{
p = (IDbDataParameter)command.Parameters[name];
}
p.Value = val ?? DBNull.Value;
p.Direction = param.ParameterDirection;
var s = val as string;
if (s != null)
{
if (s.Length <= 4000)
{
p.Size = 4000;
}
}
if (param.Size != null)
{
p.Size = param.Size.Value;
}
if (dbType != null)
{
p.DbType = dbType.Value;
}
if (add)
{
command.Parameters.Add(p);
}
param.AttachedParam = p;
}
}
}
/// <summary>
/// All the names of the param in the bag, use Get to yank them out
/// </summary>
public IEnumerable<string> ParameterNames
{
get
{
return parameters.Select(p => p.Key);
}
}
/// <summary>
/// Get the value of a parameter
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <returns>The value, note DBNull.Value is not returned, instead the value is returned as null</returns>
public T Get<T>(string name)
{
var val = parameters[Clean(name)].AttachedParam.Value;
if (val == DBNull.Value)
{
if (default(T) != null)
{
throw new ApplicationException("Attempting to cast a DBNull to a non nullable type!");
}
return default(T);
}
return (T)val;
}
}
/// <summary>
/// This class represents a SQL string, it can be used if you need to denote your parameter is a Char vs VarChar vs nVarChar vs nChar
/// </summary>
sealed partial class DbString : Dapper.SqlMapper.ICustomQueryParameter
{
/// <summary>
/// Create a new DbString
/// </summary>
public DbString() { Length = -1; }
/// <summary>
/// Ansi vs Unicode
/// </summary>
public bool IsAnsi { get; set; }
/// <summary>
/// Fixed length
/// </summary>
public bool IsFixedLength { get; set; }
/// <summary>
/// Length of the string -1 for max
/// </summary>
public int Length { get; set; }
/// <summary>
/// The value of the string
/// </summary>
public string Value { get; set; }
/// <summary>
/// Add the parameter to the command... internal use only
/// </summary>
/// <param name="command"></param>
/// <param name="name"></param>
public void AddParameter(IDbCommand command, string name)
{
if (IsFixedLength && Length == -1)
{
throw new InvalidOperationException("If specifying IsFixedLength, a Length must also be specified");
}
var param = command.CreateParameter();
param.ParameterName = name;
param.Value = (object)Value ?? DBNull.Value;
if (Length == -1 && Value != null && Value.Length <= 4000)
{
param.Size = 4000;
}
else
{
param.Size = Length;
}
param.DbType = IsAnsi ? (IsFixedLength ? DbType.AnsiStringFixedLength : DbType.AnsiString) : (IsFixedLength ? DbType.StringFixedLength : DbType.String);
command.Parameters.Add(param);
}
}
/// <summary>
/// Handles variances in features per DBMS
/// </summary>
partial class FeatureSupport
{
/// <summary>
/// Dictionary of supported features index by connection type name
/// </summary>
private static readonly Dictionary<string, FeatureSupport> FeatureList = new Dictionary<string, FeatureSupport>(StringComparer.InvariantCultureIgnoreCase) {
{"sqlserverconnection", new FeatureSupport { Arrays = false}},
{"npgsqlconnection", new FeatureSupport {Arrays = true}}
};
/// <summary>
/// Gets the featureset based on the passed connection
/// </summary>
public static FeatureSupport Get(IDbConnection connection)
{
string name = connection.GetType().Name;
FeatureSupport features;
return FeatureList.TryGetValue(name, out features) ? features : FeatureList.Values.First();
}
/// <summary>
/// True if the db supports array columns e.g. Postgresql
/// </summary>
public bool Arrays { get; set; }
}
/// <summary>
/// Represents simple memeber map for one of target parameter or property or field to source DataReader column
/// </summary>
sealed partial class SimpleMemberMap : SqlMapper.IMemberMap
{
private readonly string _columnName;
private readonly PropertyInfo _property;
private readonly FieldInfo _field;
private readonly ParameterInfo _parameter;
/// <summary>
/// Creates instance for simple property mapping
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <param name="property">Target property</param>
public SimpleMemberMap(string columnName, PropertyInfo property)
{
if (columnName == null)
throw new ArgumentNullException("columnName");
if (property == null)
throw new ArgumentNullException("property");
_columnName = columnName;
_property = property;
}
/// <summary>
/// Creates instance for simple field mapping
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <param name="field">Target property</param>
public SimpleMemberMap(string columnName, FieldInfo field)
{
if (columnName == null)
throw new ArgumentNullException("columnName");
if (field == null)
throw new ArgumentNullException("field");
_columnName = columnName;
_field = field;
}
/// <summary>
/// Creates instance for simple constructor parameter mapping
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <param name="parameter">Target constructor parameter</param>
public SimpleMemberMap(string columnName, ParameterInfo parameter)
{
if (columnName == null)
throw new ArgumentNullException("columnName");
if (parameter == null)
throw new ArgumentNullException("parameter");
_columnName = columnName;
_parameter = parameter;
}
/// <summary>
/// DataReader column name
/// </summary>
public string ColumnName
{
get { return _columnName; }
}
/// <summary>
/// Target member type
/// </summary>
public Type MemberType
{
get
{
if (_field != null)
return _field.FieldType;
if (_property != null)
return _property.PropertyType;
if (_parameter != null)
return _parameter.ParameterType;
return null;
}
}
/// <summary>
/// Target property
/// </summary>
public PropertyInfo Property
{
get { return _property; }
}
/// <summary>
/// Target field
/// </summary>
public FieldInfo Field
{
get { return _field; }
}
/// <summary>
/// Target constructor parameter
/// </summary>
public ParameterInfo Parameter
{
get { return _parameter; }
}
}
/// <summary>
/// Represents default type mapping strategy used by Dapper
/// </summary>
sealed partial class DefaultTypeMap : SqlMapper.ITypeMap
{
private readonly List<FieldInfo> _fields;
private readonly List<PropertyInfo> _properties;
private readonly Type _type;
/// <summary>
/// Creates default type map
/// </summary>
/// <param name="type">Entity type</param>
public DefaultTypeMap(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
_fields = GetSettableFields(type);
_properties = GetSettableProps(type);
_type = type;
}
internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
{
return propertyInfo.DeclaringType == type ?
propertyInfo.GetSetMethod(true) :
propertyInfo.DeclaringType.GetProperty(propertyInfo.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetSetMethod(true);
}
internal static List<PropertyInfo> GetSettableProps(Type t)
{
return t
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => GetPropertySetter(p, t) != null)
.ToList();
}
internal static List<FieldInfo> GetSettableFields(Type t)
{
return t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToList();
}
/// <summary>
/// Finds best constructor
/// </summary>
/// <param name="names">DataReader column names</param>
/// <param name="types">DataReader column types</param>
/// <returns>Matching constructor or default one</returns>
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo ctor in constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)).ThenBy(c => c.GetParameters().Length))
{
ParameterInfo[] ctorParameters = ctor.GetParameters();
if (ctorParameters.Length == 0)
return ctor;
if (ctorParameters.Length != types.Length)
continue;
int i = 0;
for (; i < ctorParameters.Length; i++)
{
if (!String.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
break;
if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
continue;
var unboxedType = Nullable.GetUnderlyingType(ctorParameters[i].ParameterType) ?? ctorParameters[i].ParameterType;
if (unboxedType != types[i]
&& !(unboxedType.IsEnum && Enum.GetUnderlyingType(unboxedType) == types[i])
&& !(unboxedType == typeof(char) && types[i] == typeof(string)))
break;
}
if (i == ctorParameters.Length)
return ctor;
}
return null;
}
/// <summary>
/// Gets mapping for constructor parameter
/// </summary>
/// <param name="constructor">Constructor to resolve</param>
/// <param name="columnName">DataReader column name</param>
/// <returns>Mapping implementation</returns>
public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
{
var parameters = constructor.GetParameters();
return new SimpleMemberMap(columnName, parameters.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase)));
}
/// <summary>
/// Gets member mapping for column
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <returns>Mapping implementation</returns>
public SqlMapper.IMemberMap GetMember(string columnName)
{
var property = _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
?? _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));
if (property != null)
return new SimpleMemberMap(columnName, property);
var field = _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
?? _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));
if (field != null)
return new SimpleMemberMap(columnName, field);
return null;
}
}
/// <summary>
/// Implements custom property mapping by user provided criteria (usually presence of some custom attribute with column to member mapping)
/// </summary>
sealed partial class CustomPropertyTypeMap : SqlMapper.ITypeMap
{
private readonly Type _type;
private readonly Func<Type, string, PropertyInfo> _propertySelector;
/// <summary>
/// Creates custom property mapping
/// </summary>
/// <param name="type">Target entity type</param>
/// <param name="propertySelector">Property selector based on target type and DataReader column name</param>
public CustomPropertyTypeMap(Type type, Func<Type, string, PropertyInfo> propertySelector)
{
if (type == null)
throw new ArgumentNullException("type");
if (propertySelector == null)
throw new ArgumentNullException("propertySelector");
_type = type;
_propertySelector = propertySelector;
}
/// <summary>
/// Always returns default constructor
/// </summary>
/// <param name="names">DataReader column names</param>
/// <param name="types">DataReader column types</param>
/// <returns>Default constructor</returns>
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
return _type.GetConstructor(new Type[0]);
}
/// <summary>
/// Not impelmeneted as far as default constructor used for all cases
/// </summary>
/// <param name="constructor"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
{
throw new NotSupportedException();
}
/// <summary>
/// Returns property based on selector strategy
/// </summary>
/// <param name="columnName">DataReader column name</param>
/// <returns>Poperty member map</returns>
public SqlMapper.IMemberMap GetMember(string columnName)
{
var prop = _propertySelector(_type, columnName);
return prop != null ? new SimpleMemberMap(columnName, prop) : null;
}
}
// Define DAPPER_MAKE_PRIVATE if you reference Dapper by source
// and you like to make the Dapper types private (in order to avoid
// conflicts with other projects that also reference Dapper by source)
#if !DAPPER_MAKE_PRIVATE
public partial class SqlMapper
{
}
public partial class DynamicParameters
{
}
public partial class DbString
{
}
public partial class SimpleMemberMap
{
}
public partial class DefaultTypeMap
{
}
public partial class CustomPropertyTypeMap
{
}
public partial class FeatureSupport
{
}
#endif
} | zzfenglove-dapper | Dapper NET40/SqlMapper.cs | C# | asf20 | 154,167 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Collections.Concurrent;
using System.Reflection.Emit;
using System.Threading;
using System.Runtime.CompilerServices;
using Dapper;
namespace Dapper.Contrib.Extensions
{
public static class SqlMapperExtensions
{
public interface IProxy
{
bool IsDirty { get; set; }
}
private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> KeyProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
private static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> TypeProperties = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
private static readonly ConcurrentDictionary<RuntimeTypeHandle, string> GetQueries = new ConcurrentDictionary<RuntimeTypeHandle, string>();
private static readonly ConcurrentDictionary<RuntimeTypeHandle, string> TypeTableName = new ConcurrentDictionary<RuntimeTypeHandle, string>();
private static readonly Dictionary<string, ISqlAdapter> AdapterDictionary = new Dictionary<string, ISqlAdapter>() {
{"sqlconnection", new SqlServerAdapter()},
{"npgsqlconnection", new PostgresAdapter()}
};
private static IEnumerable<PropertyInfo> KeyPropertiesCache(Type type)
{
IEnumerable<PropertyInfo> pi;
if (KeyProperties.TryGetValue(type.TypeHandle,out pi))
{
return pi;
}
var allProperties = TypePropertiesCache(type);
var keyProperties = allProperties.Where(p => p.GetCustomAttributes(true).Any(a => a is KeyAttribute)).ToList();
if (keyProperties.Count == 0)
{
var idProp = allProperties.Where(p => p.Name.ToLower() == "id").FirstOrDefault();
if (idProp != null)
{
keyProperties.Add(idProp);
}
}
KeyProperties[type.TypeHandle] = keyProperties;
return keyProperties;
}
private static IEnumerable<PropertyInfo> TypePropertiesCache(Type type)
{
IEnumerable<PropertyInfo> pis;
if (TypeProperties.TryGetValue(type.TypeHandle, out pis))
{
return pis;
}
var properties = type.GetProperties().Where(IsWriteable);
TypeProperties[type.TypeHandle] = properties;
return properties;
}
public static bool IsWriteable(PropertyInfo pi)
{
object[] attributes = pi.GetCustomAttributes(typeof (WriteAttribute), false);
if (attributes.Length == 1)
{
WriteAttribute write = (WriteAttribute) attributes[0];
return write.Write;
}
return true;
}
/// <summary>
/// Returns a single entity by a single id from table "Ts". T must be of interface type.
/// Id must be marked with [Key] attribute.
/// Created entity is tracked/intercepted for changes and used by the Update() extension.
/// </summary>
/// <typeparam name="T">Interface type to create and populate</typeparam>
/// <param name="connection">Open SqlConnection</param>
/// <param name="id">Id of the entity to get, must be marked with [Key] attribute</param>
/// <returns>Entity of T</returns>
public static T Get<T>(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
{
var type = typeof(T);
string sql;
if (!GetQueries.TryGetValue(type.TypeHandle, out sql))
{
var keys = KeyPropertiesCache(type);
if (keys.Count() > 1)
throw new DataException("Get<T> only supports an entity with a single [Key] property");
if (keys.Count() == 0)
throw new DataException("Get<T> only supports en entity with a [Key] property");
var onlyKey = keys.First();
var name = GetTableName(type);
// TODO: pluralizer
// TODO: query information schema and only select fields that are both in information schema and underlying class / interface
sql = "select * from " + name + " where " + onlyKey.Name + " = @id";
GetQueries[type.TypeHandle] = sql;
}
var dynParms = new DynamicParameters();
dynParms.Add("@id", id);
T obj = null;
if (type.IsInterface)
{
var res = connection.Query(sql, dynParms).FirstOrDefault() as IDictionary<string, object>;
if (res == null)
return (T)((object)null);
obj = ProxyGenerator.GetInterfaceProxy<T>();
foreach (var property in TypePropertiesCache(type))
{
var val = res[property.Name];
property.SetValue(obj, val, null);
}
((IProxy)obj).IsDirty = false; //reset change tracking and return
}
else
{
obj = connection.Query<T>(sql, dynParms, transaction: transaction, commandTimeout: commandTimeout).FirstOrDefault();
}
return obj;
}
private static string GetTableName(Type type)
{
string name;
if (!TypeTableName.TryGetValue(type.TypeHandle, out name))
{
name = type.Name + "s";
if (type.IsInterface && name.StartsWith("I"))
name = name.Substring(1);
//NOTE: This as dynamic trick should be able to handle both our own Table-attribute as well as the one in EntityFramework
var tableattr = type.GetCustomAttributes(false).Where(attr => attr.GetType().Name == "TableAttribute").SingleOrDefault() as
dynamic;
if (tableattr != null)
name = tableattr.Name;
TypeTableName[type.TypeHandle] = name;
}
return name;
}
/// <summary>
/// Inserts an entity into table "Ts" and returns identity id.
/// </summary>
/// <param name="connection">Open SqlConnection</param>
/// <param name="entityToInsert">Entity to insert</param>
/// <returns>Identity of inserted entity</returns>
public static long Insert<T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
{
var type = typeof(T);
var name = GetTableName(type);
var sbColumnList = new StringBuilder(null);
var allProperties = TypePropertiesCache(type);
var keyProperties = KeyPropertiesCache(type);
var allPropertiesExceptKey = allProperties.Except(keyProperties);
for (var i = 0; i < allPropertiesExceptKey.Count(); i++)
{
var property = allPropertiesExceptKey.ElementAt(i);
sbColumnList.AppendFormat("[{0}]", property.Name);
if (i < allPropertiesExceptKey.Count() - 1)
sbColumnList.Append(", ");
}
var sbParameterList = new StringBuilder(null);
for (var i = 0; i < allPropertiesExceptKey.Count(); i++)
{
var property = allPropertiesExceptKey.ElementAt(i);
sbParameterList.AppendFormat("@{0}", property.Name);
if (i < allPropertiesExceptKey.Count() - 1)
sbParameterList.Append(", ");
}
ISqlAdapter adapter = GetFormatter(connection);
int id = adapter.Insert(connection, transaction, commandTimeout, name, sbColumnList.ToString(), sbParameterList.ToString(), keyProperties, entityToInsert);
return id;
}
/// <summary>
/// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
/// </summary>
/// <typeparam name="T">Type to be updated</typeparam>
/// <param name="connection">Open SqlConnection</param>
/// <param name="entityToUpdate">Entity to be updated</param>
/// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
public static bool Update<T>(this IDbConnection connection, T entityToUpdate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
{
var proxy = entityToUpdate as IProxy;
if (proxy != null)
{
if (!proxy.IsDirty) return false;
}
var type = typeof(T);
var keyProperties = KeyPropertiesCache(type);
if (!keyProperties.Any())
throw new ArgumentException("Entity must have at least one [Key] property");
var name = GetTableName(type);
var sb = new StringBuilder();
sb.AppendFormat("update {0} set ", name);
var allProperties = TypePropertiesCache(type);
var nonIdProps = allProperties.Where(a => !keyProperties.Contains(a));
for (var i = 0; i < nonIdProps.Count(); i++)
{
var property = nonIdProps.ElementAt(i);
sb.AppendFormat("{0} = @{1}", property.Name, property.Name);
if (i < nonIdProps.Count() - 1)
sb.AppendFormat(", ");
}
sb.Append(" where ");
for (var i = 0; i < keyProperties.Count(); i++)
{
var property = keyProperties.ElementAt(i);
sb.AppendFormat("{0} = @{1}", property.Name, property.Name);
if (i < keyProperties.Count() - 1)
sb.AppendFormat(" and ");
}
var updated = connection.Execute(sb.ToString(), entityToUpdate, commandTimeout: commandTimeout, transaction: transaction);
return updated > 0;
}
/// <summary>
/// Delete entity in table "Ts".
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="connection">Open SqlConnection</param>
/// <param name="entityToDelete">Entity to delete</param>
/// <returns>true if deleted, false if not found</returns>
public static bool Delete<T>(this IDbConnection connection, T entityToDelete, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
{
if (entityToDelete == null)
throw new ArgumentException("Cannot Delete null Object", "entityToDelete");
var type = typeof(T);
var keyProperties = KeyPropertiesCache(type);
if (keyProperties.Count() == 0)
throw new ArgumentException("Entity must have at least one [Key] property");
var name = GetTableName(type);
var sb = new StringBuilder();
sb.AppendFormat("delete from {0} where ", name);
for (var i = 0; i < keyProperties.Count(); i++)
{
var property = keyProperties.ElementAt(i);
sb.AppendFormat("{0} = @{1}", property.Name, property.Name);
if (i < keyProperties.Count() - 1)
sb.AppendFormat(" and ");
}
var deleted = connection.Execute(sb.ToString(), entityToDelete, transaction: transaction, commandTimeout: commandTimeout);
return deleted > 0;
}
public static ISqlAdapter GetFormatter(IDbConnection connection)
{
string name = connection.GetType().Name.ToLower();
if (!AdapterDictionary.ContainsKey(name))
return new SqlServerAdapter();
return AdapterDictionary[name];
}
class ProxyGenerator
{
private static readonly Dictionary<Type, object> TypeCache = new Dictionary<Type, object>();
private static AssemblyBuilder GetAsmBuilder(string name)
{
var assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(new AssemblyName { Name = name },
AssemblyBuilderAccess.Run); //NOTE: to save, use RunAndSave
return assemblyBuilder;
}
public static T GetClassProxy<T>()
{
// A class proxy could be implemented if all properties are virtual
// otherwise there is a pretty dangerous case where internal actions will not update dirty tracking
throw new NotImplementedException();
}
public static T GetInterfaceProxy<T>()
{
Type typeOfT = typeof(T);
object k;
if (TypeCache.TryGetValue(typeOfT, out k))
{
return (T)k;
}
var assemblyBuilder = GetAsmBuilder(typeOfT.Name);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("SqlMapperExtensions." + typeOfT.Name); //NOTE: to save, add "asdasd.dll" parameter
var interfaceType = typeof(Dapper.Contrib.Extensions.SqlMapperExtensions.IProxy);
var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "_" + Guid.NewGuid(),
TypeAttributes.Public | TypeAttributes.Class);
typeBuilder.AddInterfaceImplementation(typeOfT);
typeBuilder.AddInterfaceImplementation(interfaceType);
//create our _isDirty field, which implements IProxy
var setIsDirtyMethod = CreateIsDirtyProperty(typeBuilder);
// Generate a field for each property, which implements the T
foreach (var property in typeof(T).GetProperties())
{
var isId = property.GetCustomAttributes(true).Any(a => a is KeyAttribute);
CreateProperty<T>(typeBuilder, property.Name, property.PropertyType, setIsDirtyMethod, isId);
}
var generatedType = typeBuilder.CreateType();
//assemblyBuilder.Save(name + ".dll"); //NOTE: to save, uncomment
var generatedObject = Activator.CreateInstance(generatedType);
TypeCache.Add(typeOfT, generatedObject);
return (T)generatedObject;
}
private static MethodInfo CreateIsDirtyProperty(TypeBuilder typeBuilder)
{
var propType = typeof(bool);
var field = typeBuilder.DefineField("_" + "IsDirty", propType, FieldAttributes.Private);
var property = typeBuilder.DefineProperty("IsDirty",
System.Reflection.PropertyAttributes.None,
propType,
new Type[] { propType });
const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.NewSlot | MethodAttributes.SpecialName |
MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig;
// Define the "get" and "set" accessor methods
var currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + "IsDirty",
getSetAttr,
propType,
Type.EmptyTypes);
var currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);
var currSetPropMthdBldr = typeBuilder.DefineMethod("set_" + "IsDirty",
getSetAttr,
null,
new Type[] { propType });
var currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ret);
property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
var getMethod = typeof(Dapper.Contrib.Extensions.SqlMapperExtensions.IProxy).GetMethod("get_" + "IsDirty");
var setMethod = typeof(Dapper.Contrib.Extensions.SqlMapperExtensions.IProxy).GetMethod("set_" + "IsDirty");
typeBuilder.DefineMethodOverride(currGetPropMthdBldr, getMethod);
typeBuilder.DefineMethodOverride(currSetPropMthdBldr, setMethod);
return currSetPropMthdBldr;
}
private static void CreateProperty<T>(TypeBuilder typeBuilder, string propertyName, Type propType, MethodInfo setIsDirtyMethod, bool isIdentity)
{
//Define the field and the property
var field = typeBuilder.DefineField("_" + propertyName, propType, FieldAttributes.Private);
var property = typeBuilder.DefineProperty(propertyName,
System.Reflection.PropertyAttributes.None,
propType,
new Type[] { propType });
const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.Virtual |
MethodAttributes.HideBySig;
// Define the "get" and "set" accessor methods
var currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName,
getSetAttr,
propType,
Type.EmptyTypes);
var currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);
var currSetPropMthdBldr = typeBuilder.DefineMethod("set_" + propertyName,
getSetAttr,
null,
new Type[] { propType });
//store value in private field and set the isdirty flag
var currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldc_I4_1);
currSetIL.Emit(OpCodes.Call, setIsDirtyMethod);
currSetIL.Emit(OpCodes.Ret);
//TODO: Should copy all attributes defined by the interface?
if (isIdentity)
{
var keyAttribute = typeof(KeyAttribute);
var myConstructorInfo = keyAttribute.GetConstructor(new Type[] { });
var attributeBuilder = new CustomAttributeBuilder(myConstructorInfo, new object[] { });
property.SetCustomAttribute(attributeBuilder);
}
property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
var getMethod = typeof(T).GetMethod("get_" + propertyName);
var setMethod = typeof(T).GetMethod("set_" + propertyName);
typeBuilder.DefineMethodOverride(currGetPropMthdBldr, getMethod);
typeBuilder.DefineMethodOverride(currSetPropMthdBldr, setMethod);
}
}
}
[AttributeUsage(AttributeTargets.Class)]
public class TableAttribute : Attribute
{
public TableAttribute(string tableName)
{
Name = tableName;
}
public string Name { get; private set; }
}
// do not want to depend on data annotations that is not in client profile
[AttributeUsage(AttributeTargets.Property)]
public class KeyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property)]
public class WriteAttribute : Attribute
{
public WriteAttribute(bool write)
{
Write = write;
}
public bool Write { get; private set; }
}
}
public interface ISqlAdapter
{
int Insert(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert);
}
public class SqlServerAdapter : ISqlAdapter
{
public int Insert(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{
string cmd = String.Format("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList);
connection.Execute(cmd, entityToInsert, transaction: transaction, commandTimeout: commandTimeout);
//NOTE: would prefer to use IDENT_CURRENT('tablename') or IDENT_SCOPE but these are not available on SQLCE
var r = connection.Query("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout);
int id = (int)r.First().id;
if (keyProperties.Any())
keyProperties.First().SetValue(entityToInsert, id, null);
return id;
}
}
public class PostgresAdapter : ISqlAdapter
{
public int Insert(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList);
// If no primary key then safe to assume a join table with not too much data to return
if (!keyProperties.Any())
sb.Append(" RETURNING *");
else
{
sb.Append(" RETURNING ");
bool first = true;
foreach (var property in keyProperties)
{
if (!first)
sb.Append(", ");
first = false;
sb.Append(property.Name);
}
}
var results = connection.Query(sb.ToString(), entityToInsert, transaction: transaction, commandTimeout: commandTimeout);
// Return the key by assinging the corresponding property in the object - by product is that it supports compound primary keys
int id = 0;
foreach (var p in keyProperties)
{
var value = ((IDictionary<string, object>)results.First())[p.Name.ToLower()];
p.SetValue(entityToInsert, value, null);
if (id == 0)
id = Convert.ToInt32(value);
}
return id;
}
} | zzfenglove-dapper | Dapper.Contrib/SqlMapperExtensions.cs | C# | asf20 | 23,712 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper.Contrib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Dapper.Contrib")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6dde1c15-4e92-45e7-93fc-88778d15ff31")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | Dapper.Contrib/Properties/AssemblyInfo.cs | C# | asf20 | 1,458 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlMapper
{
static class Assert
{
public static void IsEqualTo<T>(this T obj, T other)
{
if (!Equals(obj, other))
{
throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
}
}
public static void IsSequenceEqualTo<T>(this IEnumerable<T> obj, IEnumerable<T> other)
{
if (!(obj ?? new T[0]).SequenceEqual(other ?? new T[0]))
{
throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
}
}
public static void IsFalse(this bool b)
{
if (b)
{
throw new ApplicationException("Expected false");
}
}
public static void IsTrue(this bool b)
{
if (!b)
{
throw new ApplicationException("Expected true");
}
}
public static void IsNull(this object obj)
{
if (obj != null)
{
throw new ApplicationException("Expected null");
}
}
public static void IsNotNull(this object obj)
{
if (obj == null)
{
throw new ApplicationException("Expected not null");
}
}
}
}
| zzfenglove-dapper | Tests/Assert.cs | C# | asf20 | 1,539 |
using System.Data;
using NHibernate;
using NHibernate.Cfg;
namespace SqlMapper.NHibernate
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure(@"..\..\NHibernate\hibernate.cfg.xml");
configuration.AddAssembly(typeof(Post).Assembly);
configuration.AddXmlFile(@"..\..\NHibernate\Post.hbm.xml");
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static IStatelessSession OpenSession()
{
return SessionFactory.OpenStatelessSession();
}
}
}
| zzfenglove-dapper | Tests/NHibernate/NHibernateHelper.cs | C# | asf20 | 977 |
namespace SqlMapper.Linq2Sql
{
public partial class Post
{
/*
public int Bloat { get; set; }
public int Bloat1 { get; set; }
public int Bloat2 { get; set; }
public int Bloat3 { get; set; }
public int Bloat4 { get; set; }
public int Bloat5 { get; set; }
public int Bloat6 { get; set; }
public int Bloat7 { get; set; }
public int Bloat8 { get; set; }
public int Bloat10 { get; set; }
public int Bloat11 { get; set; }
public int Bloat12 { get; set; }
public int Bloat13 { get; set; }
public int Bloat14 { get; set; }
public int Bloat15 { get; set; }
public int Bloat16 { get; set; }
public int Bloat17 { get; set; }
public int Bloat18 { get; set; }
*/
}
}
| zzfenglove-dapper | Tests/Linq2Sql/Post.cs | C# | asf20 | 860 |
using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Linq;
namespace SqlMapper
{
[ServiceStack.DataAnnotations.Alias("Posts")]
[Soma.Core.Table(Name = "Posts")]
class Post
{
[Soma.Core.Id(Soma.Core.IdKind.Identity)]
public int Id { get; set; }
public string Text { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastChangeDate { get; set; }
public int? Counter1 { get; set; }
public int? Counter2 { get; set; }
public int? Counter3 { get; set; }
public int? Counter4 { get; set; }
public int? Counter5 { get; set; }
public int? Counter6 { get; set; }
public int? Counter7 { get; set; }
public int? Counter8 { get; set; }
public int? Counter9 { get; set; }
}
class Program
{
public static readonly string connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True";
public static SqlConnection GetOpenConnection()
{
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
static void RunPerformanceTests()
{
var test = new PerformanceTests();
const int iterations = 500;
Console.WriteLine("Running {0} iterations that load up a post entity", iterations);
test.Run(iterations);
}
static void Main()
{
#if DEBUG
RunTests();
#else
EnsureDBSetup();
RunPerformanceTests();
#endif
Console.WriteLine("(end of tests; press any key)");
Console.ReadKey();
}
private static void EnsureDBSetup()
{
using (var cnn = GetOpenConnection())
{
var cmd = cnn.CreateCommand();
cmd.CommandText = @"
if (OBJECT_ID('Posts') is null)
begin
create table Posts
(
Id int identity primary key,
[Text] varchar(max) not null,
CreationDate datetime not null,
LastChangeDate datetime not null,
Counter1 int,
Counter2 int,
Counter3 int,
Counter4 int,
Counter5 int,
Counter6 int,
Counter7 int,
Counter8 int,
Counter9 int
)
set nocount on
declare @i int
declare @c int
declare @id int
set @i = 0
while @i <= 5001
begin
insert Posts ([Text],CreationDate, LastChangeDate) values (replicate('x', 2000), GETDATE(), GETDATE())
set @id = @@IDENTITY
set @i = @i + 1
end
end
";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
}
}
private static void RunTests()
{
var tester = new Tests();
int fail = 0;
MethodInfo[] methods = typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var activeTests = methods.Where(m => Attribute.IsDefined(m, typeof(ActiveTestAttribute))).ToArray();
if (activeTests.Length != 0) methods = activeTests;
foreach (var method in methods)
{
Console.Write("Running " + method.Name);
try
{
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
} catch(TargetInvocationException tie)
{
fail++;
Console.WriteLine(" - " + tie.InnerException.Message);
}catch (Exception ex)
{
fail++;
Console.WriteLine(" - " + ex.Message);
}
}
Console.WriteLine();
if(fail == 0)
{
Console.WriteLine("(all tests successful)");
}
else
{
Console.WriteLine("#### FAILED: {0}", fail);
}
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class ActiveTestAttribute : Attribute {}
}
| zzfenglove-dapper | Tests/Program.cs | C# | asf20 | 4,252 |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
namespace Massive
{
public static class ObjectExtensions
{
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args)
{
foreach (var item in args)
{
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(ExpandoObject))
{
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
}
else
{
p.Value = item;
}
//from DataChomp
if (item.GetType() == typeof(string))
p.Size = 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr)
{
var result = new List<dynamic>();
while (rdr.Read())
{
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr)
{
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (int i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), rdr[i]);
return e;
}
/// <summary>
/// Turns the object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o)
{
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
}
else
{
var props = o.GetType().GetProperties();
foreach (var item in props)
{
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy)
{
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel
{
DbProviderFactory _factory;
#pragma warning disable 0649
string _connectionString;
#pragma warning restore 0649
public DynamicModel(string connectionStringName = "", string tableName = "", string primaryKeyField = "")
{
_factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
/*
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
if (connectionStringName == "")
connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
var _providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
_providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
else
{
throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'");
}
_factory = DbProviderFactories.GetFactory(_providerName);
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
*/
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
{
using (var conn = OpenConnection())
{
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args)
{
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader())
{
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args)
{
object result = null;
using (var conn = OpenConnection())
{
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
DbCommand CreateCommand(string sql, DbConnection conn, params object[] args)
{
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection()
{
var result = _factory.CreateConnection();
result.ConnectionString = _connectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things)
{
var commands = new List<DbCommand>();
foreach (var item in things)
{
if (HasPrimaryKey(item))
{
commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item)));
}
else
{
commands.Add(CreateInsertCommand(item));
}
}
return commands;
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things)
{
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual int Execute(DbCommand command)
{
return Execute(new DbCommand[] { command });
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands)
{
var result = 0;
using (var conn = OpenConnection())
{
using (var tx = conn.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o)
{
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o)
{
object result = null;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateInsertCommand(object o)
{
DbCommand result = null;
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
if (counter > 0)
{
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
}
else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(object o, object key)
{
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var args = new List<object>();
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.CurrentCultureIgnoreCase) && item.Value != null)
{
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString());
counter++;
}
}
if (counter > 0)
{
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
}
else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args)
{
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null)
{
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new object[] { key };
}
else if (!string.IsNullOrEmpty(where))
{
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual object Insert(object o)
{
dynamic result = 0;
using (var conn = OpenConnection())
{
var cmd = CreateInsertCommand(o);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
result = cmd.ExecuteScalar();
}
return result;
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key)
{
return Execute(CreateUpdateCommand(o, key));
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args)
{
return Execute(CreateDeleteCommand(where: where, key: key, args: args));
}
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args)
{
string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.CurrentCultureIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return Query(string.Format(sql, columns, TableName), args);
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new ExpandoObject();
var countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
if (String.IsNullOrEmpty(orderBy))
orderBy = PrimaryKeyField;
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase))
{
where = "WHERE " + where;
}
}
var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row >={0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*")
{
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
var items = Query(sql, key).ToList();
return items.FirstOrDefault();
}
}
} | zzfenglove-dapper | Tests/Massive/Massive.cs | C# | asf20 | 18,687 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using System.Linq.Expressions;
using SubSonic.Schema;
using System.Collections;
using SubSonic;
using SubSonic.Repository;
using System.ComponentModel;
using System.Data.Common;
namespace SubSonic
{
/// <summary>
/// A class which represents the Posts table in the tempdb Database.
/// </summary>
public partial class Post: IActiveRecord
{
#region Built-in testing
static TestRepository<Post> _testRepo;
static void SetTestRepo(){
_testRepo = _testRepo ?? new TestRepository<Post>(new SubSonic.tempdbDB());
}
public static void ResetTestRepo(){
_testRepo = null;
SetTestRepo();
}
public static void Setup(List<Post> testlist){
SetTestRepo();
foreach (var item in testlist)
{
_testRepo._items.Add(item);
}
}
public static void Setup(Post item) {
SetTestRepo();
_testRepo._items.Add(item);
}
public static void Setup(int testItems) {
SetTestRepo();
for(int i=0;i<testItems;i++){
Post item=new Post();
_testRepo._items.Add(item);
}
}
public bool TestMode = false;
#endregion
IRepository<Post> _repo;
ITable tbl;
bool _isNew;
public bool IsNew(){
return _isNew;
}
public void SetIsLoaded(bool isLoaded){
_isLoaded=isLoaded;
if(isLoaded)
OnLoaded();
}
public void SetIsNew(bool isNew){
_isNew=isNew;
}
bool _isLoaded;
public bool IsLoaded(){
return _isLoaded;
}
List<IColumn> _dirtyColumns;
public bool IsDirty(){
return _dirtyColumns.Count>0;
}
public List<IColumn> GetDirtyColumns (){
return _dirtyColumns;
}
SubSonic.tempdbDB _db;
public Post(string connectionString, string providerName) {
_db=new SubSonic.tempdbDB(connectionString, providerName);
Init();
}
void Init(){
TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
_dirtyColumns=new List<IColumn>();
if(TestMode){
Post.SetTestRepo();
_repo=_testRepo;
}else{
_repo = new SubSonicRepository<Post>(_db);
}
tbl=_repo.GetTable();
SetIsNew(true);
OnCreated();
}
public Post(){
_db=new SubSonic.tempdbDB();
Init();
}
partial void OnCreated();
partial void OnLoaded();
partial void OnSaved();
partial void OnChanged();
public IList<IColumn> Columns{
get{
return tbl.Columns;
}
}
public Post(Expression<Func<Post, bool>> expression):this() {
SetIsLoaded(_repo.Load(this,expression));
}
internal static IRepository<Post> GetRepo(string connectionString, string providerName){
SubSonic.tempdbDB db;
if(String.IsNullOrEmpty(connectionString)){
db=new SubSonic.tempdbDB();
}else{
db=new SubSonic.tempdbDB(connectionString, providerName);
}
IRepository<Post> _repo;
if(db.TestMode){
Post.SetTestRepo();
_repo=_testRepo;
}else{
_repo = new SubSonicRepository<Post>(db);
}
return _repo;
}
internal static IRepository<Post> GetRepo(){
return GetRepo("","");
}
public static Post SingleOrDefault(Expression<Func<Post, bool>> expression) {
var repo = GetRepo();
var results=repo.Find(expression);
Post single=null;
if(results.Count() > 0){
single=results.ToList()[0];
single.OnLoaded();
single.SetIsLoaded(true);
single.SetIsNew(false);
}
return single;
}
public static Post SingleOrDefault(Expression<Func<Post, bool>> expression,string connectionString, string providerName) {
var repo = GetRepo(connectionString,providerName);
var results=repo.Find(expression);
Post single=null;
if(results.Count() > 0){
single=results.ToList()[0];
}
return single;
}
public static bool Exists(Expression<Func<Post, bool>> expression,string connectionString, string providerName) {
return All(connectionString,providerName).Any(expression);
}
public static bool Exists(Expression<Func<Post, bool>> expression) {
return All().Any(expression);
}
public static IList<Post> Find(Expression<Func<Post, bool>> expression) {
var repo = GetRepo();
return repo.Find(expression).ToList();
}
public static IList<Post> Find(Expression<Func<Post, bool>> expression,string connectionString, string providerName) {
var repo = GetRepo(connectionString,providerName);
return repo.Find(expression).ToList();
}
public static IQueryable<Post> All(string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetAll();
}
public static IQueryable<Post> All() {
return GetRepo().GetAll();
}
public static PagedList<Post> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
}
public static PagedList<Post> GetPaged(string sortBy, int pageIndex, int pageSize) {
return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
}
public static PagedList<Post> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
}
public static PagedList<Post> GetPaged(int pageIndex, int pageSize) {
return GetRepo().GetPaged(pageIndex, pageSize);
}
public string KeyName()
{
return "Id";
}
public object KeyValue()
{
return this.Id;
}
public void SetKeyValue(object value) {
if (value != null && value!=DBNull.Value) {
var settable = value.ChangeTypeTo<int>();
this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
}
}
public override string ToString(){
return this.Text.ToString();
}
public override bool Equals(object obj){
if(obj.GetType()==typeof(Post)){
Post compare=(Post)obj;
return compare.KeyValue()==this.KeyValue();
}else{
return base.Equals(obj);
}
}
public override int GetHashCode() {
return this.Id;
}
public string DescriptorValue()
{
return this.Text.ToString();
}
public string DescriptorColumn() {
return "Text";
}
public static string GetKeyColumn()
{
return "Id";
}
public static string GetDescriptorColumn()
{
return "Text";
}
#region ' Foreign Keys '
#endregion
int _Id;
public int Id
{
get { return _Id; }
set
{
if(_Id!=value){
_Id=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
string _Text;
public string Text
{
get { return _Text; }
set
{
if(_Text!=value){
_Text=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Text");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime _CreationDate;
public DateTime CreationDate
{
get { return _CreationDate; }
set
{
if(_CreationDate!=value){
_CreationDate=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreationDate");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime _LastChangeDate;
public DateTime LastChangeDate
{
get { return _LastChangeDate; }
set
{
if(_LastChangeDate!=value){
_LastChangeDate=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LastChangeDate");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter1;
public int? Counter1
{
get { return _Counter1; }
set
{
if(_Counter1!=value){
_Counter1=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter1");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter2;
public int? Counter2
{
get { return _Counter2; }
set
{
if(_Counter2!=value){
_Counter2=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter2");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter3;
public int? Counter3
{
get { return _Counter3; }
set
{
if(_Counter3!=value){
_Counter3=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter3");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter4;
public int? Counter4
{
get { return _Counter4; }
set
{
if(_Counter4!=value){
_Counter4=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter4");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter5;
public int? Counter5
{
get { return _Counter5; }
set
{
if(_Counter5!=value){
_Counter5=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter5");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter6;
public int? Counter6
{
get { return _Counter6; }
set
{
if(_Counter6!=value){
_Counter6=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter6");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter7;
public int? Counter7
{
get { return _Counter7; }
set
{
if(_Counter7!=value){
_Counter7=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter7");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter8;
public int? Counter8
{
get { return _Counter8; }
set
{
if(_Counter8!=value){
_Counter8=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter8");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _Counter9;
public int? Counter9
{
get { return _Counter9; }
set
{
if(_Counter9!=value){
_Counter9=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Counter9");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
public DbCommand GetUpdateCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
}
public DbCommand GetInsertCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
}
public DbCommand GetDeleteCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
}
public void Update(){
Update(_db.DataProvider);
}
public void Update(IDataProvider provider){
if(this._dirtyColumns.Count>0){
_repo.Update(this,provider);
_dirtyColumns.Clear();
}
OnSaved();
}
public void Add(){
Add(_db.DataProvider);
}
public void Add(IDataProvider provider){
var key=KeyValue();
if(key==null){
var newKey=_repo.Add(this,provider);
this.SetKeyValue(newKey);
}else{
_repo.Add(this,provider);
}
SetIsNew(false);
OnSaved();
}
public void Save() {
Save(_db.DataProvider);
}
public void Save(IDataProvider provider) {
if (_isNew) {
Add(provider);
} else {
Update(provider);
}
}
public void Delete(IDataProvider provider) {
_repo.Delete(KeyValue());
}
public void Delete() {
Delete(_db.DataProvider);
}
public static void Delete(Expression<Func<Post, bool>> expression) {
var repo = GetRepo();
repo.DeleteMany(expression);
}
public void Load(IDataReader rdr) {
Load(rdr, true);
}
public void Load(IDataReader rdr, bool closeReader) {
if (rdr.Read()) {
try {
rdr.Load(this);
SetIsNew(false);
SetIsLoaded(true);
} catch {
SetIsLoaded(false);
throw;
}
}else{
SetIsLoaded(false);
}
if (closeReader)
rdr.Dispose();
}
}
}
| zzfenglove-dapper | Tests/SubSonic/ActiveRecord.cs | C# | asf20 | 19,669 |
using System;
using SubSonic.Schema;
using System.Collections.Generic;
using SubSonic.DataProviders;
using System.Data;
namespace SubSonic {
/// <summary>
/// Table: Posts
/// Primary Key: Id
/// </summary>
public class PostsTable: DatabaseTable {
public PostsTable(IDataProvider provider):base("Posts",provider){
ClassName = "Post";
SchemaName = "dbo";
Columns.Add(new DatabaseColumn("Id", this)
{
IsPrimaryKey = true,
DataType = DbType.Int32,
IsNullable = false,
AutoIncrement = true,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Text", this)
{
IsPrimaryKey = false,
DataType = DbType.AnsiString,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = -1
});
Columns.Add(new DatabaseColumn("CreationDate", this)
{
IsPrimaryKey = false,
DataType = DbType.DateTime,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("LastChangeDate", this)
{
IsPrimaryKey = false,
DataType = DbType.DateTime,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter1", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter2", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter3", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter4", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter5", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter6", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter7", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter8", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
Columns.Add(new DatabaseColumn("Counter9", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0
});
}
public IColumn Id{
get{
return this.GetColumn("Id");
}
}
public static string IdColumn{
get{
return "Id";
}
}
public IColumn Text{
get{
return this.GetColumn("Text");
}
}
public static string TextColumn{
get{
return "Text";
}
}
public IColumn CreationDate{
get{
return this.GetColumn("CreationDate");
}
}
public static string CreationDateColumn{
get{
return "CreationDate";
}
}
public IColumn LastChangeDate{
get{
return this.GetColumn("LastChangeDate");
}
}
public static string LastChangeDateColumn{
get{
return "LastChangeDate";
}
}
public IColumn Counter1{
get{
return this.GetColumn("Counter1");
}
}
public static string Counter1Column{
get{
return "Counter1";
}
}
public IColumn Counter2{
get{
return this.GetColumn("Counter2");
}
}
public static string Counter2Column{
get{
return "Counter2";
}
}
public IColumn Counter3{
get{
return this.GetColumn("Counter3");
}
}
public static string Counter3Column{
get{
return "Counter3";
}
}
public IColumn Counter4{
get{
return this.GetColumn("Counter4");
}
}
public static string Counter4Column{
get{
return "Counter4";
}
}
public IColumn Counter5{
get{
return this.GetColumn("Counter5");
}
}
public static string Counter5Column{
get{
return "Counter5";
}
}
public IColumn Counter6{
get{
return this.GetColumn("Counter6");
}
}
public static string Counter6Column{
get{
return "Counter6";
}
}
public IColumn Counter7{
get{
return this.GetColumn("Counter7");
}
}
public static string Counter7Column{
get{
return "Counter7";
}
}
public IColumn Counter8{
get{
return this.GetColumn("Counter8");
}
}
public static string Counter8Column{
get{
return "Counter8";
}
}
public IColumn Counter9{
get{
return this.GetColumn("Counter9");
}
}
public static string Counter9Column{
get{
return "Counter9";
}
}
}
} | zzfenglove-dapper | Tests/SubSonic/Structs.cs | C# | asf20 | 8,716 |
using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using SubSonic.Linq.Structure;
using SubSonic.Query;
using SubSonic.Schema;
using System.Data.Common;
using System.Collections.Generic;
namespace SubSonic
{
public partial class tempdbDB : IQuerySurface
{
public IDataProvider DataProvider;
public DbQueryProvider provider;
public static IDataProvider DefaultDataProvider { get; set; }
public bool TestMode
{
get
{
return DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
}
}
public tempdbDB()
{
if (DefaultDataProvider == null) {
DataProvider = ProviderFactory.GetProvider("Smackdown.Properties.Settings.tempdbConnectionString");
}
else {
DataProvider = DefaultDataProvider;
}
Init();
}
public tempdbDB(string connectionStringName)
{
DataProvider = ProviderFactory.GetProvider(connectionStringName);
Init();
}
public tempdbDB(string connectionString, string providerName)
{
DataProvider = ProviderFactory.GetProvider(connectionString,providerName);
Init();
}
public ITable FindByPrimaryKey(string pkName)
{
return DataProvider.Schema.Tables.SingleOrDefault(x => x.PrimaryKey.Name.Equals(pkName, StringComparison.InvariantCultureIgnoreCase));
}
public Query<T> GetQuery<T>()
{
return new Query<T>(provider);
}
public ITable FindTable(string tableName)
{
return DataProvider.FindTable(tableName);
}
public IDataProvider Provider
{
get { return DataProvider; }
set {DataProvider=value;}
}
public DbQueryProvider QueryProvider
{
get { return provider; }
}
BatchQuery _batch = null;
public void Queue<T>(IQueryable<T> qry)
{
if (_batch == null)
_batch = new BatchQuery(Provider, QueryProvider);
_batch.Queue(qry);
}
public void Queue(ISqlQuery qry)
{
if (_batch == null)
_batch = new BatchQuery(Provider, QueryProvider);
_batch.Queue(qry);
}
public void ExecuteTransaction(IList<DbCommand> commands)
{
if(!TestMode)
{
using(var connection = commands[0].Connection)
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var trans = connection.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Transaction = trans;
cmd.Connection = connection;
cmd.ExecuteNonQuery();
}
trans.Commit();
}
connection.Close();
}
}
}
public IDataReader ExecuteBatch()
{
if (_batch == null)
throw new InvalidOperationException("There's nothing in the queue");
if(!TestMode)
return _batch.ExecuteReader();
return null;
}
public Query<Post> Posts { get; set; }
#region ' Aggregates and SubSonic Queries '
public Select SelectColumns(params string[] columns)
{
return new Select(DataProvider, columns);
}
public Select Select
{
get { return new Select(this.Provider); }
}
public Insert Insert
{
get { return new Insert(this.Provider); }
}
public Update<T> Update<T>() where T:new()
{
return new Update<T>(this.Provider);
}
public SqlQuery Delete<T>(Expression<Func<T,bool>> column) where T:new()
{
LambdaExpression lamda = column;
SqlQuery result = new Delete<T>(this.Provider);
result = result.From<T>();
result.Constraints=lamda.ParseConstraints().ToList();
return result;
}
public SqlQuery Max<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = DataProvider.FindTable(objectName).Name;
return new Select(DataProvider, new Aggregate(colName, AggregateFunction.Max)).From(tableName);
}
public SqlQuery Min<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Min)).From(tableName);
}
public SqlQuery Sum<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Sum)).From(tableName);
}
public SqlQuery Avg<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Avg)).From(tableName);
}
public SqlQuery Count<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Count)).From(tableName);
}
public SqlQuery Variance<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Var)).From(tableName);
}
public SqlQuery StandardDeviation<T>(Expression<Func<T,object>> column)
{
LambdaExpression lamda = column;
string colName = lamda.ParseObjectValue();
string objectName = typeof(T).Name;
string tableName = this.Provider.FindTable(objectName).Name;
return new Select(this.Provider, new Aggregate(colName, AggregateFunction.StDev)).From(tableName);
}
#endregion
void Init()
{
provider = new DbQueryProvider(this.Provider);
#region ' Query Defs '
Posts = new Query<Post>(provider);
#endregion
#region ' Schemas '
if(DataProvider.Schema.Tables.Count == 0)
{
DataProvider.Schema.Tables.Add(new PostsTable(DataProvider));
}
#endregion
}
#region ' Helpers '
internal static DateTime DateTimeNowTruncatedDownToSecond() {
var now = DateTime.Now;
return now.AddTicks(-now.Ticks % TimeSpan.TicksPerSecond);
}
#endregion
}
} | zzfenglove-dapper | Tests/SubSonic/Context.cs | C# | asf20 | 8,399 |
| zzfenglove-dapper | Tests/SubSonic/StoredProcedures.cs | C# | asf20 | 10 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Smackdown")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Smackdown")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("77246f63-77a4-4d9f-a4d6-62282d67c8be")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | Tests/Properties/AssemblyInfo.cs | C# | asf20 | 1,448 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Common;
using System.Data;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Reflection.Emit;
namespace PetaPoco
{
// Poco's marked [Explicit] require all column properties to be marked
[AttributeUsage(AttributeTargets.Class)]
public class ExplicitColumns : Attribute
{
}
// For non-explicit pocos, causes a property to be ignored
[AttributeUsage(AttributeTargets.Property)]
public class Ignore : Attribute
{
}
// For explicit pocos, marks property as a column and optionally supplies column name
[AttributeUsage(AttributeTargets.Property)]
public class Column : Attribute
{
public Column() { }
public Column(string name) { Name = name; }
public string Name { get; set; }
}
// For explicit pocos, marks property as a result column and optionally supplies column name
[AttributeUsage(AttributeTargets.Property)]
public class ResultColumn : Column
{
public ResultColumn() { }
public ResultColumn(string name) : base(name) { }
}
// Specify the table name of a poco
[AttributeUsage(AttributeTargets.Class)]
public class TableName : Attribute
{
public TableName(string tableName)
{
Value = tableName;
}
public string Value { get; private set; }
}
// Specific the primary key of a poco class
[AttributeUsage(AttributeTargets.Class)]
public class PrimaryKey : Attribute
{
public PrimaryKey(string primaryKey)
{
Value = primaryKey;
}
public string Value { get; private set; }
}
// Results from paged request
public class Page<T> where T : new()
{
public long CurrentPage { get; set; }
public long TotalPages { get; set; }
public long TotalItems { get; set; }
public long ItemsPerPage { get; set; }
public List<T> Items { get; set; }
}
// Optionally provide and implementation of this to Database.Mapper
public interface IMapper
{
void GetTableInfo(Type t, ref string tableName, ref string primaryKey);
bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn);
Func<object, object> GetValueConverter(PropertyInfo pi, Type SourceType);
}
// Database class ... this is where most of the action happens
public class Database : IDisposable
{
public Database(DbConnection connection)
{
_sharedConnection = connection;
_connectionString = connection.ConnectionString;
_sharedConnectionDepth = 2; // Prevent closing external connection
CommonConstruct();
}
public Database(string connectionString, string providerName)
{
_connectionString = connectionString;
_providerName = providerName;
CommonConstruct();
}
public Database(string connectionStringName)
{
// Use first?
if (connectionStringName == "")
connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
// Work out connection string and provider name
var providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
else
{
throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'");
}
// Store factory and connection string
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = providerName;
CommonConstruct();
}
// Common initialization
void CommonConstruct()
{
_transactionDepth = 0;
EnableAutoSelect = true;
EnableNamedParams = true;
ForceDateTimesToUtc = true;
if (_providerName != null)
_factory = DbProviderFactories.GetFactory(_providerName);
if (_connectionString != null && _connectionString.IndexOf("Allow User Variables=true") >= 0 && IsMySql())
_paramPrefix = "?";
}
// Automatically close one open shared connection
public void Dispose()
{
if (_sharedConnectionDepth > 0)
CloseSharedConnection();
}
// Who are we talking too?
bool IsMySql() { return string.Compare(_providerName, "MySql.Data.MySqlClient", true) == 0; }
bool IsSqlServer() { return string.Compare(_providerName, "System.Data.SqlClient", true) == 0; }
// Open a connection (can be nested)
public void OpenSharedConnection()
{
if (_sharedConnectionDepth == 0)
{
_sharedConnection = _factory.CreateConnection();
_sharedConnection.ConnectionString = _connectionString;
_sharedConnection.Open();
}
_sharedConnectionDepth++;
}
// Close a previously opened connection
public void CloseSharedConnection()
{
_sharedConnectionDepth--;
if (_sharedConnectionDepth == 0)
{
_sharedConnection.Dispose();
_sharedConnection = null;
}
}
// Helper to create a transaction scope
public Transaction Transaction
{
get
{
return new Transaction(this);
}
}
// Use by derived repo generated by T4 templates
public virtual void OnBeginTransaction() { }
public virtual void OnEndTransaction() { }
// Start a new transaction, can be nested, every call must be
// matched by a call to AbortTransaction or CompleteTransaction
// Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics
public void BeginTransaction()
{
_transactionDepth++;
if (_transactionDepth == 1)
{
OpenSharedConnection();
_transaction = _sharedConnection.BeginTransaction();
_transactionCancelled = false;
OnBeginTransaction();
}
}
// Internal helper to cleanup transaction stuff
void CleanupTransaction()
{
OnEndTransaction();
if (_transactionCancelled)
_transaction.Rollback();
else
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
CloseSharedConnection();
}
// Abort the entire outer most transaction scope
public void AbortTransaction()
{
_transactionCancelled = true;
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
// Complete the transaction
public void CompleteTransaction()
{
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
// Helper to handle named parameters from object properties
static Regex rxParams = new Regex(@"(?<!@)@\w+", RegexOptions.Compiled);
public static string ProcessParams(string _sql, object[] args_src, List<object> args_dest)
{
return rxParams.Replace(_sql, m =>
{
string param = m.Value.Substring(1);
int paramIndex;
if (int.TryParse(param, out paramIndex))
{
// Numbered parameter
if (paramIndex < 0 || paramIndex >= args_src.Length)
throw new ArgumentOutOfRangeException(string.Format("Parameter '@{0}' specified but only {1} parameters supplied (in `{2}`)", paramIndex, args_src.Length, _sql));
args_dest.Add(args_src[paramIndex]);
}
else
{
// Look for a property on one of the arguments with this name
bool found = false;
foreach (var o in args_src)
{
var pi = o.GetType().GetProperty(param);
if (pi != null)
{
args_dest.Add(pi.GetValue(o, null));
found = true;
break;
}
}
if (!found)
throw new ArgumentException(string.Format("Parameter '@{0}' specified but none of the passed arguments have a property with this name (in '{1}')", param, _sql));
}
return "@" + (args_dest.Count - 1).ToString();
}
);
}
// Add a parameter to a DB command
static void AddParam(DbCommand cmd, object item, string ParameterPrefix)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
p.Size = 4000;
p.Value = item;
}
else
{
p.Value = item;
}
}
cmd.Parameters.Add(p);
}
// Create a command
public DbCommand CreateCommand(DbConnection connection, string sql, params object[] args)
{
if (EnableNamedParams)
{
// Perform named argument replacements
var new_args = new List<object>();
sql = ProcessParams(sql, args, new_args);
args = new_args.ToArray();
}
// If we're in MySQL "Allow User Variables", we need to fix up parameter prefixes
if (_paramPrefix == "?")
{
// Convert "@parameter" -> "?parameter"
Regex paramReg = new Regex(@"(?<!@)@\w+");
sql = paramReg.Replace(sql, m => "?" + m.Value.Substring(1));
// Convert @@uservar -> @uservar and @@@systemvar -> @@systemvar
sql = sql.Replace("@@", "@");
}
// Save the last sql and args
_lastSql = sql;
_lastArgs = args;
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
cmd.Transaction = _transaction;
foreach (var item in args)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(string))
{
p.Size = (item as string).Length + 1;
if (p.Size < 4000)
p.Size = 4000;
p.Value = item;
}
else
{
p.Value = item;
}
}
cmd.Parameters.Add(p);
}
return cmd;
}
// Override this to log/capture exceptions
public virtual void OnException(Exception x)
{
System.Diagnostics.Debug.WriteLine(x.ToString());
System.Diagnostics.Debug.WriteLine(LastCommand);
}
// Execute a non-query command
public int Execute(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
return cmd.ExecuteNonQuery();
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public int Execute(Sql sql)
{
return Execute(sql.SQL, sql.Arguments);
}
// Execute and cast a scalar property
public T ExecuteScalar<T>(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
object val = cmd.ExecuteScalar();
return (T)Convert.ChangeType(val, typeof(T));
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public T ExecuteScalar<T>(Sql sql)
{
return ExecuteScalar<T>(sql.SQL, sql.Arguments);
}
Regex rxSelect = new Regex(@"^\s*SELECT\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
string AddSelectClause<T>(string sql)
{
// Already present?
if (rxSelect.IsMatch(sql))
return sql;
// Get the poco data for this type
var pd = PocoData.ForType(typeof(T));
return string.Format("SELECT {0} FROM {1} {2}", pd.QueryColumns, pd.TableName, sql);
}
public bool EnableAutoSelect { get; set; }
public bool EnableNamedParams { get; set; }
public bool ForceDateTimesToUtc { get; set; }
// Return a typed list of pocos
public List<T> Fetch<T>(string sql, params object[] args) where T : new()
{
// Auto select clause?
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
using (var r = cmd.ExecuteReader())
{
var l = new List<T>();
var pd = PocoData.ForType(typeof(T));
var factory = pd.GetFactory<T>(sql + "-" + _sharedConnection.ConnectionString + ForceDateTimesToUtc.ToString(), ForceDateTimesToUtc, r);
while (r.Read())
{
l.Add(factory(r));
}
return l;
}
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
// Optimized version when only needing a single record
public T FirstOrDefault<T>(string sql, params object[] args) where T : new()
{
// Auto select clause?
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
using (var r = cmd.ExecuteReader())
{
if (!r.Read())
return default(T);
var pd = PocoData.ForType(typeof(T));
var factory = pd.GetFactory<T>(sql + "-" + _sharedConnection.ConnectionString + ForceDateTimesToUtc.ToString(), ForceDateTimesToUtc, r);
return factory(r);
}
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
// Optimized version when only wanting a single record
public T SingleOrDefault<T>(string sql, params object[] args) where T : new()
{
// Auto select clause?
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
using (var r = cmd.ExecuteReader())
{
if (!r.Read())
return default(T);
var pd = PocoData.ForType(typeof(T));
var factory = pd.GetFactory<T>(sql + "-" + _sharedConnection.ConnectionString + ForceDateTimesToUtc.ToString(), ForceDateTimesToUtc, r);
T ret = factory(r);
if (r.Read())
throw new InvalidOperationException("Sequence contains more than one element");
return ret;
}
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
// Warning: scary regex follows
static Regex rxColumns = new Regex(@"^\s*SELECT\s+((?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|.)*?)(?<!,\s+)\bFROM\b",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
static Regex rxOrderBy = new Regex(@"\bORDER\s+BY\s+(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?(?:\s*,\s*(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?)*",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
public static bool SplitSqlForPaging(string sql, out string sqlCount, out string sqlSelectRemoved, out string sqlOrderBy)
{
sqlSelectRemoved = null;
sqlCount = null;
sqlOrderBy = null;
// Extract the columns from "SELECT <whatever> FROM"
var m = rxColumns.Match(sql);
if (!m.Success)
return false;
// Save column list and replace with COUNT(*)
Group g = m.Groups[1];
sqlCount = sql.Substring(0, g.Index) + "COUNT(*) " + sql.Substring(g.Index + g.Length);
sqlSelectRemoved = sql.Substring(g.Index);
// Look for an "ORDER BY <whatever>" clause
m = rxOrderBy.Match(sqlCount);
if (!m.Success)
return false;
g = m.Groups[0];
sqlOrderBy = g.ToString();
sqlCount = sqlCount.Substring(0, g.Index) + sqlCount.Substring(g.Index + g.Length);
return true;
}
// Fetch a page
public Page<T> Page<T>(long page, long itemsPerPage, string sql, params object[] args) where T : new()
{
// Add auto select clause
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
// Split the SQL into the bits we need
string sqlCount, sqlSelectRemoved, sqlOrderBy;
if (!SplitSqlForPaging(sql, out sqlCount, out sqlSelectRemoved, out sqlOrderBy))
throw new Exception("Unable to parse SQL statement for paged query");
// Setup the paged result
var result = new Page<T>();
result.CurrentPage = page;
result.ItemsPerPage = itemsPerPage;
result.TotalItems = ExecuteScalar<long>(sqlCount, args);
result.TotalPages = result.TotalItems / itemsPerPage;
if ((result.TotalItems % itemsPerPage) != 0)
result.TotalPages++;
// Build the SQL for the actual final result
string sqlPage;
if (IsSqlServer())
{
// Ugh really?
sqlSelectRemoved = rxOrderBy.Replace(sqlSelectRemoved, "");
sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) AS __rn, {1}) as __paged WHERE __rn>{2} AND __rn<={3}",
sqlOrderBy, sqlSelectRemoved, (page - 1) * itemsPerPage, page * itemsPerPage);
}
else
{
// Nice
sqlPage = string.Format("{0}\nLIMIT {1} OFFSET {2}", sql, itemsPerPage, (page - 1) * itemsPerPage);
}
// Get the records
result.Items = Fetch<T>(sqlPage, args);
// Done
return result;
}
public Page<T> Page<T>(long page, long itemsPerPage, Sql sql) where T : new()
{
return Page<T>(page, itemsPerPage, sql.SQL, sql.Arguments);
}
// Return an enumerable collection of pocos
public IEnumerable<T> Query<T>(string sql, params object[] args) where T : new()
{
if (EnableAutoSelect)
sql = AddSelectClause<T>(sql);
using (var conn = new ShareableConnection(this))
{
using (var cmd = CreateCommand(conn.Connection, sql, args))
{
IDataReader r;
var pd = PocoData.ForType(typeof(T));
try
{
r = cmd.ExecuteReader();
}
catch (Exception x)
{
OnException(x);
throw;
}
var factory = pd.GetFactory<T>(sql + "-" + conn.Connection.ConnectionString + ForceDateTimesToUtc.ToString(), ForceDateTimesToUtc, r);
using (r)
{
while (true)
{
T poco;
try
{
if (!r.Read())
yield break;
poco = factory(r);
}
catch (Exception x)
{
OnException(x);
throw;
}
yield return poco;
}
}
}
}
}
public List<T> Fetch<T>(Sql sql) where T : new()
{
return Fetch<T>(sql.SQL, sql.Arguments);
}
public IEnumerable<T> Query<T>(Sql sql) where T : new()
{
return Query<T>(sql.SQL, sql.Arguments);
}
public T Single<T>(string sql, params object[] args) where T : new()
{
T val = SingleOrDefault<T>(sql, args);
if (val != null)
return val;
else
throw new InvalidOperationException("The sequence contains no elements");
}
public T First<T>(string sql, params object[] args) where T : new()
{
T val = FirstOrDefault<T>(sql, args);
if (val != null)
return val;
else
throw new InvalidOperationException("The sequence contains no elements");
}
public T Single<T>(Sql sql) where T : new()
{
return Single<T>(sql.SQL, sql.Arguments);
}
public T SingleOrDefault<T>(Sql sql) where T : new()
{
return SingleOrDefault<T>(sql.SQL, sql.Arguments);
}
public T FirstOrDefault<T>(Sql sql) where T : new()
{
return FirstOrDefault<T>(sql.SQL, sql.Arguments);
}
public T First<T>(Sql sql) where T : new()
{
return First<T>(sql.SQL, sql.Arguments);
}
// Insert a poco into a table. If the poco has a property with the same name
// as the primary key the id of the new record is assigned to it. Either way,
// the new id is returned.
public object Insert(string tableName, string primaryKeyName, object poco)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, ""))
{
var pd = PocoData.ForType(poco.GetType());
var names = new List<string>();
var values = new List<string>();
var index = 0;
foreach (var i in pd.Columns)
{
// Don't insert the primary key or result only columns
if ((primaryKeyName != null && i.Key == primaryKeyName) || i.Value.ResultColumn)
continue;
names.Add(i.Key);
values.Add(string.Format("{0}{1}", _paramPrefix, index++));
AddParam(cmd, i.Value.PropertyInfo.GetValue(poco, null), _paramPrefix);
}
cmd.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2}); SELECT @@IDENTITY AS NewID;",
tableName,
string.Join(",", names.ToArray()),
string.Join(",", values.ToArray())
);
_lastSql = cmd.CommandText;
_lastArgs = values.ToArray();
// Insert the record, should get back it's ID
var id = cmd.ExecuteScalar();
// Assign the ID back to the primary key property
if (primaryKeyName != null)
{
PocoColumn pc;
if (pd.Columns.TryGetValue(primaryKeyName, out pc))
{
pc.PropertyInfo.SetValue(poco, Convert.ChangeType(id, pc.PropertyInfo.PropertyType), null);
}
}
return id;
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
// Insert an annotated poco object
public object Insert(object poco)
{
var pd = PocoData.ForType(poco.GetType());
return Insert(pd.TableName, pd.PrimaryKey, poco);
}
// Update a record with values from a poco. primary key value can be either supplied or read from the poco
public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, ""))
{
var sb = new StringBuilder();
var index = 0;
var pd = PocoData.ForType(poco.GetType());
foreach (var i in pd.Columns)
{
// Don't update the primary key, but grab the value if we don't have it
if (i.Key == primaryKeyName)
{
if (primaryKeyValue == null)
primaryKeyValue = i.Value.PropertyInfo.GetValue(poco, null);
continue;
}
// Dont update result only columns
if (i.Value.ResultColumn)
continue;
// Build the sql
if (index > 0)
sb.Append(", ");
sb.AppendFormat("{0} = {1}{2}", i.Key, _paramPrefix, index++);
// Store the parameter in the command
AddParam(cmd, i.Value.PropertyInfo.GetValue(poco, null), _paramPrefix);
}
cmd.CommandText = string.Format("UPDATE {0} SET {1} WHERE {2} = {3}{4}",
tableName,
sb.ToString(),
primaryKeyName,
_paramPrefix,
index++
);
AddParam(cmd, primaryKeyValue, _paramPrefix);
_lastSql = cmd.CommandText;
_lastArgs = new object[] { primaryKeyValue };
// Do it
return cmd.ExecuteNonQuery();
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public int Update(string tableName, string primaryKeyName, object poco)
{
return Update(tableName, primaryKeyName, poco, null);
}
public int Update(object poco)
{
return Update(poco, null);
}
public int Update(object poco, object primaryKeyValue)
{
var pd = PocoData.ForType(poco.GetType());
return Update(pd.TableName, pd.PrimaryKey, poco, primaryKeyValue);
}
public int Update<T>(string sql, params object[] args)
{
var pd = PocoData.ForType(typeof(T));
return Execute(string.Format("UPDATE {0} {1}", pd.TableName, sql), args);
}
public int Update<T>(Sql sql)
{
var pd = PocoData.ForType(typeof(T));
return Execute(new Sql(string.Format("UPDATE {0}", pd.TableName)).Append(sql));
}
public int Delete(string tableName, string primaryKeyName, object poco)
{
return Delete(tableName, primaryKeyName, poco, null);
}
public int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue)
{
// If primary key value not specified, pick it up from the object
if (primaryKeyValue == null)
{
var pd = PocoData.ForType(poco.GetType());
PocoColumn pc;
if (pd.Columns.TryGetValue(primaryKeyName, out pc))
{
primaryKeyValue = pc.PropertyInfo.GetValue(poco, null);
}
}
// Do it
var sql = string.Format("DELETE FROM {0} WHERE {1}=@0", tableName, primaryKeyName);
return Execute(sql, primaryKeyValue);
}
public int Delete(object poco)
{
var pd = PocoData.ForType(poco.GetType());
return Delete(pd.TableName, pd.PrimaryKey, poco);
}
public int Delete<T>(string sql, params object[] args)
{
var pd = PocoData.ForType(typeof(T));
return Execute(string.Format("DELETE FROM {0} {1}", pd.TableName, sql), args);
}
public int Delete<T>(Sql sql)
{
var pd = PocoData.ForType(typeof(T));
return Execute(new Sql(string.Format("DELETE FROM {0}", pd.TableName)).Append(sql));
}
// Check if a poco represents a new record
public bool IsNew(string primaryKeyName, object poco)
{
// If primary key value not specified, pick it up from the object
var pd = PocoData.ForType(poco.GetType());
PropertyInfo pi;
PocoColumn pc;
if (pd.Columns.TryGetValue(primaryKeyName, out pc))
{
pi = pc.PropertyInfo;
}
else
{
pi = poco.GetType().GetProperty(primaryKeyName);
if (pi == null)
throw new ArgumentException("The object doesn't have a property matching the primary key column name '{0}'", primaryKeyName);
}
// Get it's value
var pk = pi.GetValue(poco, null);
if (pk == null)
return true;
var type = pk.GetType();
if (type.IsValueType)
{
// Common primary key types
if (type == typeof(long))
return (long)pk == 0;
else if (type == typeof(ulong))
return (ulong)pk == 0;
else if (type == typeof(int))
return (int)pk == 0;
else if (type == typeof(uint))
return (int)pk == 0;
// Create a default instance and compare
return pk == Activator.CreateInstance(pk.GetType());
}
else
{
return pk == null;
}
}
public bool IsNew(object poco)
{
var pd = PocoData.ForType(poco.GetType());
return IsNew(pd.PrimaryKey, poco);
}
// Insert new record or Update existing record
public void Save(string tableName, string primaryKeyName, object poco)
{
if (IsNew(primaryKeyName, poco))
{
Insert(tableName, primaryKeyName, poco);
}
else
{
Update(tableName, primaryKeyName, poco);
}
}
public void Save(object poco)
{
var pd = PocoData.ForType(poco.GetType());
Save(pd.TableName, pd.PrimaryKey, poco);
}
public string LastSQL { get { return _lastSql; } }
public object[] LastArgs { get { return _lastArgs; } }
public string LastCommand
{
get
{
var sb = new StringBuilder();
if (_lastSql == null)
return "";
sb.Append(_lastSql);
if (_lastArgs != null)
{
sb.Append("\r\n\r\n");
for (int i = 0; i < _lastArgs.Length; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i, _lastArgs[i].ToString());
}
}
return sb.ToString();
}
}
public static IMapper Mapper
{
get;
set;
}
internal class PocoColumn
{
public string ColumnName;
public PropertyInfo PropertyInfo;
public bool ResultColumn;
}
internal class PocoData
{
public static PocoData ForType(Type t)
{
lock (m_PocoData)
{
PocoData pd;
if (!m_PocoData.TryGetValue(t, out pd))
{
pd = new PocoData(t);
m_PocoData.Add(t, pd);
}
return pd;
}
}
public PocoData(Type t)
{
// Get the table name
var a = t.GetCustomAttributes(typeof(TableName), true);
var tempTableName = a.Length == 0 ? t.Name : (a[0] as TableName).Value;
// Get the primary key
a = t.GetCustomAttributes(typeof(PrimaryKey), true);
var tempPrimaryKey = a.Length == 0 ? "ID" : (a[0] as PrimaryKey).Value;
// Call column mapper
if (Database.Mapper != null)
Database.Mapper.GetTableInfo(t, ref tempTableName, ref tempPrimaryKey);
TableName = tempTableName;
PrimaryKey = tempPrimaryKey;
// Work out bound properties
bool ExplicitColumns = t.GetCustomAttributes(typeof(ExplicitColumns), true).Length > 0;
Columns = new Dictionary<string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
foreach (var pi in t.GetProperties())
{
// Work out if properties is to be included
var ColAttrs = pi.GetCustomAttributes(typeof(Column), true);
if (ExplicitColumns)
{
if (ColAttrs.Length == 0)
continue;
}
else
{
if (pi.GetCustomAttributes(typeof(Ignore), true).Length != 0)
continue;
}
var pc = new PocoColumn();
pc.PropertyInfo = pi;
// Work out the DB column name
if (ColAttrs.Length > 0)
{
var colattr = (Column)ColAttrs[0];
pc.ColumnName = colattr.Name;
if ((colattr as ResultColumn) != null)
pc.ResultColumn = true;
}
if (pc.ColumnName == null)
{
pc.ColumnName = pi.Name;
if (Database.Mapper != null && !Database.Mapper.MapPropertyToColumn(pi, ref pc.ColumnName, ref pc.ResultColumn))
continue;
}
// Store it
Columns.Add(pc.ColumnName, pc);
}
// Build column list for automatic select
QueryColumns = string.Join(", ", (from c in Columns where !c.Value.ResultColumn select c.Key).ToArray());
}
// Create factory function that can convert a IDataReader record into a POCO
public Func<IDataReader, T> GetFactory<T>(string key, bool ForceDateTimesToUtc, IDataReader r)
{
lock (PocoFactories)
{
// Have we already created it?
object factory;
if (PocoFactories.TryGetValue(key, out factory))
return factory as Func<IDataReader, T>;
lock (m_Converters)
{
// Create the method
var m = new DynamicMethod("petapoco_factory_" + PocoFactories.Count.ToString(), typeof(T), new Type[] { typeof(IDataReader) }, true);
var il = m.GetILGenerator();
// Running under mono?
int p = (int)Environment.OSVersion.Platform;
bool Mono = (p == 4) || (p == 6) || (p == 128);
// var poco=new T()
il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
// Enumerate all fields generating a set assignment for the column
for (int i = 0; i < r.FieldCount; i++)
{
// Get the PocoColumn for this db column, ignore if not known
PocoColumn pc;
if (!Columns.TryGetValue(r.GetName(i), out pc))
continue;
// Get the source type for this column
var srcType = r.GetFieldType(i);
var dstType = pc.PropertyInfo.PropertyType;
// "if (!rdr.IsDBNull(i))"
il.Emit(OpCodes.Ldarg_0); // poco,rdr
il.Emit(OpCodes.Ldc_I4, i); // poco,rdr,i
il.Emit(OpCodes.Callvirt, fnIsDBNull); // poco,bool
var lblNext = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, lblNext); // poco
il.Emit(OpCodes.Dup); // poco,poco
// Do we need to install a converter?
Func<object, object> converter = null;
// Get converter from the mapper
if (Database.Mapper != null)
{
converter = Database.Mapper.GetValueConverter(pc.PropertyInfo, srcType);
}
// Standard DateTime->Utc mapper
if (ForceDateTimesToUtc && converter == null && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?)))
{
converter = delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); };
}
// Forced type conversion
if (converter == null && !dstType.IsAssignableFrom(srcType))
{
converter = delegate(object src) { return Convert.ChangeType(src, dstType, null); };
}
// Fast
bool Handled = false;
if (converter == null)
{
var valuegetter = typeof(IDataRecord).GetMethod("Get" + srcType.Name, new Type[] { typeof(int) });
if (valuegetter != null
&& valuegetter.ReturnType == srcType
&& (valuegetter.ReturnType == dstType || valuegetter.ReturnType == Nullable.GetUnderlyingType(dstType)))
{
il.Emit(OpCodes.Ldarg_0); // *,rdr
il.Emit(OpCodes.Ldc_I4, i); // *,rdr,i
il.Emit(OpCodes.Callvirt, valuegetter); // *,value
// Mono give IL error if we don't explicitly create Nullable instance for the assignment
if (Mono && Nullable.GetUnderlyingType(dstType) != null)
{
il.Emit(OpCodes.Newobj, dstType.GetConstructor(new Type[] { Nullable.GetUnderlyingType(dstType) }));
}
il.Emit(OpCodes.Callvirt, pc.PropertyInfo.GetSetMethod()); // poco
Handled = true;
}
}
// Not so fast
if (!Handled)
{
// Setup stack for call to converter
int converterIndex = -1;
if (converter != null)
{
// Add the converter
converterIndex = m_Converters.Count;
m_Converters.Add(converter);
// Generate IL to push the converter onto the stack
il.Emit(OpCodes.Ldsfld, fldConverters);
il.Emit(OpCodes.Ldc_I4, converterIndex);
il.Emit(OpCodes.Callvirt, fnListGetItem); // Converter
}
// "value = rdr.GetValue(i)"
il.Emit(OpCodes.Ldarg_0); // *,rdr
il.Emit(OpCodes.Ldc_I4, i); // *,rdr,i
il.Emit(OpCodes.Callvirt, fnGetValue); // *,value
// Call the converter
if (converter != null)
il.Emit(OpCodes.Callvirt, fnInvoke);
// Assign it
il.Emit(OpCodes.Unbox_Any, pc.PropertyInfo.PropertyType); // poco,poco,value
il.Emit(OpCodes.Callvirt, pc.PropertyInfo.GetSetMethod()); // poco
}
il.MarkLabel(lblNext);
}
il.Emit(OpCodes.Ret);
// Cache it, return it
var del = (Func<IDataReader, T>)m.CreateDelegate(typeof(Func<IDataReader, T>));
PocoFactories.Add(key, del);
return del;
}
}
}
static Dictionary<Type, PocoData> m_PocoData = new Dictionary<Type, PocoData>();
static List<Func<object, object>> m_Converters = new List<Func<object, object>>();
static MethodInfo fnGetValue = typeof(IDataRecord).GetMethod("GetValue", new Type[] { typeof(int) });
static MethodInfo fnIsDBNull = typeof(IDataRecord).GetMethod("IsDBNull");
static FieldInfo fldConverters = typeof(PocoData).GetField("m_Converters", BindingFlags.Static | BindingFlags.GetField | BindingFlags.NonPublic);
static MethodInfo fnListGetItem = typeof(List<Func<object, object>>).GetProperty("Item").GetGetMethod();
static MethodInfo fnInvoke = typeof(Func<object, object>).GetMethod("Invoke");
public string TableName { get; private set; }
public string PrimaryKey { get; private set; }
public string QueryColumns { get; private set; }
public Dictionary<string, PocoColumn> Columns { get; private set; }
Dictionary<string, object> PocoFactories = new Dictionary<string, object>();
}
// ShareableConnection represents either a shared connection used by a transaction,
// or a one-off connection if not in a transaction.
// Non-shared connections are disposed
class ShareableConnection : IDisposable
{
public ShareableConnection(Database db)
{
_db = db;
_db.OpenSharedConnection();
}
public DbConnection Connection
{
get
{
return _db._sharedConnection;
}
}
Database _db;
public void Dispose()
{
_db.CloseSharedConnection();
}
}
// Member variables
string _connectionString;
string _providerName;
DbProviderFactory _factory;
DbConnection _sharedConnection;
DbTransaction _transaction;
int _sharedConnectionDepth;
int _transactionDepth;
bool _transactionCancelled;
string _lastSql;
object[] _lastArgs;
string _paramPrefix = "@";
}
// Transaction object helps maintain transaction depth counts
public class Transaction : IDisposable
{
public Transaction(Database db)
{
_db = db;
_db.BeginTransaction();
}
public void Complete()
{
_db.CompleteTransaction();
_db = null;
}
public void Dispose()
{
if (_db != null)
_db.AbortTransaction();
}
Database _db;
}
// Simple helper class for building SQL statments
public class Sql
{
public Sql()
{
}
public Sql(string sql, params object[] args)
{
_sql = sql;
_args = args;
}
string _sql;
object[] _args;
Sql _rhs;
string _sqlFinal;
object[] _argsFinal;
void Build()
{
// already built?
if (_sqlFinal != null)
return;
// Build it
var sb = new StringBuilder();
var args = new List<object>();
Build(sb, args, null);
_sqlFinal = sb.ToString();
_argsFinal = args.ToArray();
}
public string SQL
{
get
{
Build();
return _sqlFinal;
}
}
public object[] Arguments
{
get
{
Build();
return _argsFinal;
}
}
public Sql Append(Sql sql)
{
if (_rhs != null)
_rhs.Append(sql);
else
_rhs = sql;
return this;
}
public Sql Append(string sql, params object[] args)
{
return Append(new Sql(sql, args));
}
public Sql Where(string sql, params object[] args)
{
return Append(new Sql("WHERE " + sql, args));
}
public Sql OrderBy(params object[] args)
{
return Append(new Sql("ORDER BY " + String.Join(", ", (from x in args select x.ToString()).ToArray())));
}
public Sql Select(params object[] args)
{
return Append(new Sql("SELECT " + String.Join(", ", (from x in args select x.ToString()).ToArray())));
}
public Sql From(params object[] args)
{
return Append(new Sql("FROM " + String.Join(", ", (from x in args select x.ToString()).ToArray())));
}
static bool Is(Sql sql, string sqltype)
{
return sql != null && sql._sql != null && sql._sql.StartsWith(sqltype, StringComparison.InvariantCultureIgnoreCase);
}
public void Build(StringBuilder sb, List<object> args, Sql lhs)
{
if (!String.IsNullOrEmpty(_sql))
{
// Add SQL to the string
if (sb.Length > 0)
{
sb.Append("\n");
}
var sql = Database.ProcessParams(_sql, _args, args);
if (Is(lhs, "WHERE ") && Is(this, "WHERE "))
sql = "AND " + sql.Substring(6);
if (Is(lhs, "ORDER BY ") && Is(this, "ORDER BY "))
sql = ", " + sql.Substring(9);
sb.Append(sql);
}
// Now do rhs
if (_rhs != null)
_rhs.Build(sb, args, this);
}
}
}
| zzfenglove-dapper | Tests/PetaPoco/PetaPoco.cs | C# | asf20 | 39,974 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dapper_NET45
{
public class Class1
{
}
}
| zzfenglove-dapper | Dapper NET45/Class1.cs | C# | asf20 | 195 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace Dapper
{
public static partial class SqlMapper
{
/// <summary>
/// Execute a query asynchronously using .NET 4.5 Task.
/// </summary>
public static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
{
var identity = new Identity(sql, commandType, cnn, typeof(T), param == null ? null : param.GetType(), null);
var info = GetCacheInfo(identity);
var cmd = (DbCommand)SetupCommand(cnn, transaction, sql, info.ParamReader, param, commandTimeout, commandType);
using (var reader = await cmd.ExecuteReaderAsync())
{
return ExecuteReader<T>(reader, identity, info).ToList();
}
}
/// <summary>
/// Maps a query to objects
/// </summary>
/// <typeparam name="TFirst">The first type in the recordset</typeparam>
/// <typeparam name="TSecond">The second type in the recordset</typeparam>
/// <typeparam name="TReturn">The return type</typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout</param>
/// <param name="commandType">Is it a stored proc or a batch?</param>
/// <returns></returns>
public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return MultiMapAsync<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Maps a query to objects
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
/// <param name="commandTimeout">Number of seconds before command execution timeout</param>
/// <param name="commandType"></param>
/// <returns></returns>
public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return await MultiMapAsync<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 4 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return MultiMapAsync<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 5 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static async Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return await MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 6 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TSixth"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
/// <summary>
/// Perform a multi mapping query with 7 input parameters
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TThird"></typeparam>
/// <typeparam name="TFourth"></typeparam>
/// <typeparam name="TFifth"></typeparam>
/// <typeparam name="TSixth"></typeparam>
/// <typeparam name="TSeventh"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="cnn"></param>
/// <param name="sql"></param>
/// <param name="map"></param>
/// <param name="param"></param>
/// <param name="transaction"></param>
/// <param name="buffered"></param>
/// <param name="splitOn"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
return MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
}
static async Task<IEnumerable<TReturn>> MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, object map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType)
{
var identity = new Identity(sql, commandType, cnn, typeof(TFirst), (object)param == null ? null : ((object)param).GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) });
var info = GetCacheInfo(identity);
var cmd = (DbCommand)SetupCommand(cnn, transaction, sql, info.ParamReader, param, commandTimeout, commandType);
using (var reader = await cmd.ExecuteReaderAsync())
{
var results = MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, null, map, null, null, splitOn, null, null, reader, identity);
return buffered ? results.ToList() : results;
}
}
private static IEnumerable<T> ExecuteReader<T>(IDataReader reader, Identity identity, CacheInfo info)
{
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(typeof(T), reader, 0, -1, false));
SetQueryCache(identity, info);
}
var func = tuple.Func;
while (reader.Read())
{
yield return (T)func(reader);
}
}
}
} | zzfenglove-dapper | Dapper NET45/SqlMapperAsync.cs | C# | asf20 | 11,591 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper NET45")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dapper NET45")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec9ad659-1358-4d01-be77-ce45cd40b2f8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | Dapper NET45/Properties/AssemblyInfo.cs | C# | asf20 | 1,436 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Dapper.Contrib.Tests
{
/// <summary>
/// Assert extensions borrowed from Sam's code in DapperTests
/// </summary>
static class Assert
{
public static void IsEqualTo<T>(this T obj, T other)
{
if (!obj.Equals(other))
{
throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
}
}
public static void IsSequenceEqualTo<T>(this IEnumerable<T> obj, IEnumerable<T> other)
{
if (!obj.SequenceEqual(other))
{
throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
}
}
public static void IsFalse(this bool b)
{
if (b)
{
throw new ApplicationException("Expected false");
}
}
public static void IsTrue(this bool b)
{
if (!b)
{
throw new ApplicationException("Expected true");
}
}
public static void IsNull(this object obj)
{
if (obj != null)
{
throw new ApplicationException("Expected null");
}
}
}
} | zzfenglove-dapper | Dapper.Contrib.Tests/Assert.cs | C# | asf20 | 1,398 |
using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Dapper.Contrib.Tests
{
class Program
{
static void Main(string[] args)
{
Setup();
RunTests();
}
private static void Setup()
{
var projLoc = Assembly.GetAssembly(typeof(Program)).Location;
var projFolder = Path.GetDirectoryName(projLoc);
if (File.Exists(projFolder + "\\Test.sdf"))
File.Delete(projFolder + "\\Test.sdf");
var connectionString = "Data Source = " + projFolder + "\\Test.sdf;";
var engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
using (var connection = new SqlCeConnection(connectionString))
{
connection.Open();
connection.Execute(@" create table Users (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, Age int not null) ");
connection.Execute(@" create table Automobiles (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null) ");
connection.Execute(@" create table Results (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, [Order] int not null) ");
}
Console.WriteLine("Created database");
}
private static void RunTests()
{
var tester = new Tests();
foreach (var method in typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
}
Console.ReadKey();
}
}
}
| zzfenglove-dapper | Dapper.Contrib.Tests/Program.cs | C# | asf20 | 1,938 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper.Contrib.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Dapper.Contrib.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d5920b6-d6af-41ca-b851-803ac922d933")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzfenglove-dapper | Dapper.Contrib.Tests/Properties/AssemblyInfo.cs | C# | asf20 | 1,470 |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
namespace Dapper.Rainbow
{
public abstract class SqlCompactDatabase<TDatabase> : Database<TDatabase>, IDisposable where TDatabase : Database<TDatabase>, new()
{
public class SqlCompactTable<T> : Table<T>
{
public SqlCompactTable(Database<TDatabase> database, string likelyTableName)
: base(database, likelyTableName)
{
}
/// <summary>
/// Insert a row into the db
/// </summary>
/// <param name="data">Either DynamicParameters or an anonymous type or concrete type</param>
/// <returns></returns>
public override int? Insert(dynamic data)
{
var o = (object)data;
List<string> paramNames = GetParamNames(o);
paramNames.Remove("Id");
string cols = string.Join(",", paramNames);
string cols_params = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "insert " + TableName + " (" + cols + ") values (" + cols_params + ")";
if (database.Execute(sql, o) != 1)
{
return null;
}
return (int)database.Query<decimal>("SELECT @@IDENTITY AS LastInsertedId").Single();
}
}
public static TDatabase Init(DbConnection connection)
{
TDatabase db = new TDatabase();
db.InitDatabase(connection, 0);
return db;
}
internal override Action<TDatabase> CreateTableConstructorForTable()
{
return CreateTableConstructor(typeof(SqlCompactTable<>));
}
}
}
| zzfenglove-dapper | Dapper.Rainbow/SqlCompactDatabase.cs | C# | asf20 | 1,863 |
/*
License: http://www.apache.org/licenses/LICENSE-2.0
Home page: http://code.google.com/p/dapper-dot-net/
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Dapper;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text;
using System.Data.Common;
using System.Diagnostics;
using System.Reflection.Emit;
namespace Dapper
{
/// <summary>
/// A container for a database, assumes all the tables have an Id column named Id
/// </summary>
/// <typeparam name="TDatabase"></typeparam>
public abstract class Database<TDatabase> : IDisposable where TDatabase : Database<TDatabase>, new()
{
public class Table<T, TId>
{
internal Database<TDatabase> database;
internal string tableName;
internal string likelyTableName;
public Table(Database<TDatabase> database, string likelyTableName)
{
this.database = database;
this.likelyTableName = likelyTableName;
}
public string TableName
{
get
{
tableName = tableName ?? database.DetermineTableName<T>(likelyTableName);
return tableName;
}
}
/// <summary>
/// Insert a row into the db
/// </summary>
/// <param name="data">Either DynamicParameters or an anonymous type or concrete type</param>
/// <returns></returns>
public virtual int? Insert(dynamic data)
{
var o = (object)data;
List<string> paramNames = GetParamNames(o);
paramNames.Remove("Id");
string cols = string.Join(",", paramNames);
string cols_params = string.Join(",", paramNames.Select(p => "@" + p));
var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + cols_params + ") select cast(scope_identity() as int)";
return database.Query<int?>(sql, o).Single();
}
/// <summary>
/// Update a record in the DB
/// </summary>
/// <param name="id"></param>
/// <param name="data"></param>
/// <returns></returns>
public int Update(TId id, dynamic data)
{
List<string> paramNames = GetParamNames((object)data);
var builder = new StringBuilder();
builder.Append("update ").Append(TableName).Append(" set ");
builder.AppendLine(string.Join(",", paramNames.Where(n => n != "Id").Select(p => p + "= @" + p)));
builder.Append("where Id = @Id");
DynamicParameters parameters = new DynamicParameters(data);
parameters.Add("Id", id);
return database.Execute(builder.ToString(), parameters);
}
/// <summary>
/// Delete a record for the DB
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool Delete(TId id)
{
return database.Execute("delete from " + TableName + " where Id = @id", new { id }) > 0;
}
/// <summary>
/// Grab a record with a particular Id from the DB
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T Get(TId id)
{
return database.Query<T>("select * from " + TableName + " where Id = @id", new { id }).FirstOrDefault();
}
public virtual T First()
{
return database.Query<T>("select top 1 * from " + TableName).FirstOrDefault();
}
public IEnumerable<T> All()
{
return database.Query<T>("select * from " + TableName);
}
static ConcurrentDictionary<Type, List<string>> paramNameCache = new ConcurrentDictionary<Type, List<string>>();
internal static List<string> GetParamNames(object o)
{
if (o is DynamicParameters)
{
return (o as DynamicParameters).ParameterNames.ToList();
}
List<string> paramNames;
if (!paramNameCache.TryGetValue(o.GetType(), out paramNames))
{
paramNames = new List<string>();
foreach (var prop in o.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public))
{
paramNames.Add(prop.Name);
}
paramNameCache[o.GetType()] = paramNames;
}
return paramNames;
}
}
public class Table<T> : Table<T, int> {
public Table(Database<TDatabase> database, string likelyTableName)
: base(database, likelyTableName)
{
}
}
DbConnection connection;
int commandTimeout;
DbTransaction transaction;
public static TDatabase Init(DbConnection connection, int commandTimeout)
{
TDatabase db = new TDatabase();
db.InitDatabase(connection, commandTimeout);
return db;
}
internal static Action<TDatabase> tableConstructor;
internal void InitDatabase(DbConnection connection, int commandTimeout)
{
this.connection = connection;
this.commandTimeout = commandTimeout;
if (tableConstructor == null)
{
tableConstructor = CreateTableConstructorForTable();
}
tableConstructor(this as TDatabase);
}
internal virtual Action<TDatabase> CreateTableConstructorForTable()
{
return CreateTableConstructor(typeof(Table<>));
}
public void BeginTransaction(IsolationLevel isolation = IsolationLevel.ReadCommitted)
{
transaction = connection.BeginTransaction(isolation);
}
public void CommitTransaction()
{
transaction.Commit();
transaction = null;
}
public void RollbackTransaction()
{
transaction.Rollback();
transaction = null;
}
protected Action<TDatabase> CreateTableConstructor(Type tableType)
{
var dm = new DynamicMethod("ConstructInstances", null, new Type[] { typeof(TDatabase) }, true);
var il = dm.GetILGenerator();
var setters = GetType().GetProperties()
.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == tableType)
.Select(p => Tuple.Create(
p.GetSetMethod(true),
p.PropertyType.GetConstructor(new Type[] { typeof(TDatabase), typeof(string) }),
p.Name,
p.DeclaringType
));
foreach (var setter in setters)
{
il.Emit(OpCodes.Ldarg_0);
// [db]
il.Emit(OpCodes.Ldstr, setter.Item3);
// [db, likelyname]
il.Emit(OpCodes.Newobj, setter.Item2);
// [table]
var table = il.DeclareLocal(setter.Item2.DeclaringType);
il.Emit(OpCodes.Stloc, table);
// []
il.Emit(OpCodes.Ldarg_0);
// [db]
il.Emit(OpCodes.Castclass, setter.Item4);
// [db cast to container]
il.Emit(OpCodes.Ldloc, table);
// [db cast to container, table]
il.Emit(OpCodes.Callvirt, setter.Item1);
// []
}
il.Emit(OpCodes.Ret);
return (Action<TDatabase>)dm.CreateDelegate(typeof(Action<TDatabase>));
}
static ConcurrentDictionary<Type, string> tableNameMap = new ConcurrentDictionary<Type, string>();
private string DetermineTableName<T>(string likelyTableName)
{
string name;
if (!tableNameMap.TryGetValue(typeof(T), out name))
{
name = likelyTableName;
if (!TableExists(name))
{
name = "[" + typeof(T).Name + "]";
}
tableNameMap[typeof(T)] = name;
}
return name;
}
private bool TableExists(string name)
{
string schemaName = null;
name = name.Replace("[", "");
name = name.Replace("]", "");
if(name.Contains("."))
{
var parts = name.Split('.');
if (parts.Count() == 2)
{
schemaName = parts[0];
name = parts[1];
}
}
var builder = new StringBuilder("select 1 from INFORMATION_SCHEMA.TABLES where ");
if (!String.IsNullOrEmpty(schemaName)) builder.Append("TABLE_SCHEMA = @schemaName AND ");
builder.Append("TABLE_NAME = @name");
return connection.Query(builder.ToString(), new { schemaName, name }, transaction: transaction).Count() == 1;
}
public int Execute(string sql, dynamic param = null)
{
return SqlMapper.Execute(connection, sql, param as object, transaction, commandTimeout: this.commandTimeout);
}
public IEnumerable<T> Query<T>(string sql, dynamic param = null, bool buffered = true)
{
return SqlMapper.Query<T>(connection, sql, param as object, transaction, buffered, commandTimeout);
}
public IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null)
{
return SqlMapper.Query(connection, sql, map, param as object, transaction, buffered, splitOn);
}
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null)
{
return SqlMapper.Query(connection, sql, map, param as object, transaction, buffered, splitOn);
}
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null)
{
return SqlMapper.Query(connection, sql, map, param as object, transaction, buffered, splitOn);
}
public IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null)
{
return SqlMapper.Query(connection, sql, map, param as object, transaction, buffered, splitOn);
}
public IEnumerable<dynamic> Query(string sql, dynamic param = null, bool buffered = true)
{
return SqlMapper.Query(connection, sql, param as object, transaction, buffered);
}
public Dapper.SqlMapper.GridReader QueryMultiple(string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
{
return SqlMapper.QueryMultiple(connection, sql, param, transaction, commandTimeout, commandType);
}
public void Dispose()
{
if (connection.State != ConnectionState.Closed)
{
if (transaction != null)
{
transaction.Rollback();
}
connection.Close();
connection = null;
}
}
}
} | zzfenglove-dapper | Dapper.Rainbow/Database.cs | C# | asf20 | 12,742 |
/*
License: http://www.apache.org/licenses/LICENSE-2.0
Home page: http://code.google.com/p/dapper-dot-net/
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Reflection.Emit;
namespace Dapper
{
public static class Snapshotter
{
public static Snapshot<T> Start<T>(T obj)
{
return new Snapshot<T>(obj);
}
public class Snapshot<T>
{
static Func<T, T> cloner;
static Func<T, T, List<Change>> differ;
T memberWiseClone;
T trackedObject;
public Snapshot(T original)
{
memberWiseClone = Clone(original);
trackedObject = original;
}
public class Change
{
public string Name { get; set; }
public object NewValue { get; set; }
}
public DynamicParameters Diff()
{
return Diff(memberWiseClone, trackedObject);
}
private static T Clone(T myObject)
{
cloner = cloner ?? GenerateCloner();
return cloner(myObject);
}
private static DynamicParameters Diff(T original, T current)
{
var dm = new DynamicParameters();
differ = differ ?? GenerateDiffer();
foreach (var pair in differ(original, current))
{
dm.Add(pair.Name, pair.NewValue);
}
return dm;
}
static List<PropertyInfo> RelevantProperties()
{
return typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p =>
p.GetSetMethod() != null &&
p.GetGetMethod() != null &&
(p.PropertyType.IsValueType ||
p.PropertyType == typeof(string) ||
(p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
).ToList();
}
private static bool AreEqual<U>(U first, U second)
{
if (first == null && second == null) return true;
if (first == null && second != null) return false;
return first.Equals(second);
}
private static Func<T, T, List<Change>> GenerateDiffer()
{
var dm = new DynamicMethod("DoDiff", typeof(List<Change>), new Type[] { typeof(T), typeof(T) }, true);
var il = dm.GetILGenerator();
// change list
il.DeclareLocal(typeof(List<Change>));
il.DeclareLocal(typeof(Change));
il.DeclareLocal(typeof(object)); // boxed change
il.Emit(OpCodes.Newobj, typeof(List<Change>).GetConstructor(Type.EmptyTypes));
// [list]
il.Emit(OpCodes.Stloc_0);
foreach (var prop in RelevantProperties())
{
// []
il.Emit(OpCodes.Ldarg_0);
// [original]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod());
// [original prop val]
il.Emit(OpCodes.Ldarg_1);
// [original prop val, current]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod());
// [original prop val, current prop val]
il.Emit(OpCodes.Dup);
// [original prop val, current prop val, current prop val]
if (prop.PropertyType != typeof(string))
{
il.Emit(OpCodes.Box, prop.PropertyType);
// [original prop val, current prop val, current prop val boxed]
}
il.Emit(OpCodes.Stloc_2);
// [original prop val, current prop val]
il.EmitCall(OpCodes.Call, typeof(Snapshot<T>).GetMethod("AreEqual", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(new Type[] { prop.PropertyType }), null);
// [result]
Label skip = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, skip);
// []
il.Emit(OpCodes.Newobj, typeof(Change).GetConstructor(Type.EmptyTypes));
// [change]
il.Emit(OpCodes.Dup);
// [change,change]
il.Emit(OpCodes.Stloc_1);
// [change]
il.Emit(OpCodes.Ldstr, prop.Name);
// [change, name]
il.Emit(OpCodes.Callvirt, typeof(Change).GetMethod("set_Name"));
// []
il.Emit(OpCodes.Ldloc_1);
// [change]
il.Emit(OpCodes.Ldloc_2);
// [change, boxed]
il.Emit(OpCodes.Callvirt, typeof(Change).GetMethod("set_NewValue"));
// []
il.Emit(OpCodes.Ldloc_0);
// [change list]
il.Emit(OpCodes.Ldloc_1);
// [change list, change]
il.Emit(OpCodes.Callvirt, typeof(List<Change>).GetMethod("Add"));
// []
il.MarkLabel(skip);
}
il.Emit(OpCodes.Ldloc_0);
// [change list]
il.Emit(OpCodes.Ret);
return (Func<T, T, List<Change>>)dm.CreateDelegate(typeof(Func<T, T, List<Change>>));
}
// adapted from http://stackoverflow.com/a/966466/17174
private static Func<T, T> GenerateCloner()
{
Delegate myExec = null;
var dm = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true);
var ctor = typeof(T).GetConstructor(new Type[] { });
var il = dm.GetILGenerator();
il.DeclareLocal(typeof(T));
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_0);
foreach (var prop in RelevantProperties())
{
il.Emit(OpCodes.Ldloc_0);
// [clone]
il.Emit(OpCodes.Ldarg_0);
// [clone, source]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod());
// [clone, source val]
il.Emit(OpCodes.Callvirt, prop.GetSetMethod());
// []
}
// Load new constructed obj on eval stack -> 1 item on stack
il.Emit(OpCodes.Ldloc_0);
// Return constructed object. --> 0 items on stack
il.Emit(OpCodes.Ret);
myExec = dm.CreateDelegate(typeof(Func<T, T>));
return (Func<T, T>)myExec;
}
}
}
}
| zzfenglove-dapper | Dapper.Rainbow/Snapshotter.cs | C# | asf20 | 7,205 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper.Rainbow")]
[assembly: AssemblyDescription("I sample mini ORM implementation using Dapper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dapper.Rainbow")]
[assembly: AssemblyCopyright("Sam Saffron Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e763c106-eef4-4654-afcc-c28fded057e5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| zzfenglove-dapper | Dapper.Rainbow/Properties/AssemblyInfo.cs | C# | asf20 | 1,461 |
using System;
using System.Data.SqlClient;
using System.Reflection;
namespace DapperTests_NET45
{
class Program
{
static void Main()
{
RunTests();
Console.WriteLine("(end of tests; press any key)");
Console.ReadKey();
}
public static readonly string connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True";
public static SqlConnection GetOpenConnection()
{
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
private static void RunTests()
{
var tester = new Tests();
foreach (var method in typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
}
}
}
} | zzfenglove-dapper | DapperTests NET45/Program.cs | C# | asf20 | 1,067 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DapperTests NET45")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DapperTests NET45")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1f0b3016-b2c8-4ba8-b438-520b784e06a8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | zzfenglove-dapper | DapperTests NET45/Properties/AssemblyInfo.cs | C# | asf20 | 1,462 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ZzTools
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| zz-tools | trunk/ZzTools/ZzTools/Program.cs | C# | oos | 488 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ZzTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ZzTools")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b7ce8677-933d-418e-8442-fb326a51297b")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zz-tools | trunk/ZzTools/ZzTools/Properties/AssemblyInfo.cs | C# | oos | 1,364 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ZzTools
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
| zz-tools | trunk/ZzTools/ZzTools/Form1.cs | C# | oos | 357 |
<html>
<head>
<title>
Bovenkant
</title>
</head>
<body>
<h1>Welkom in Australie</h1>
Dit is de inhoud van mijn website
</body>
</html> | zzz-www | trunk/abc.html | HTML | asf20 | 191 |
package com.asd.rms;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class BaseInfoActivity extends Activity {
private final String TAG = "BaseInfoActivity";
private TelephonyManager mTelephonyManager;
Resources mRes;
TextView mDeviceId;
TextView operatorName;
TextView gsmState;
TextView roamingState;
private Button pingTestButton;
private String mPingIpAddrResult;
private String mPingHostnameResult;
private String mHttpClientTestResult;
private TextView mPingIpAddr;
private TextView mPingHostname;
private TextView mHttpClientTest;
private TextView dbm;
private TextView asu;
private TextView mLocation;
private TextView mNeighboringCids;
private Button mLockLacCid;
private TextView gprsState;
private TextView network;
private TextView mMwi;
private TextView mCfi;
private boolean mMwiValue = false;
private boolean mCfiValue = false;
private TextView callState;
private TextView resets;
private TextView attempts;
private TextView successes;
private TextView sent;
private TextView received;
private TextView sentSinceReceived;
private Spinner preferredNetworkType;
private TextView oemInfoButton;
private PhoneStateListener mPhoneStateListener = new PhoneStateListener(){
/*@Override
public void onSignalStrengthChanged(int asuValue) {//过时
super.onSignalStrengthChanged(asuValue);
asu.setText(" " + asuValue + getResources().getString(R.string.base_info_display_asu));
}*/
//信号状态
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
String val = "";
Resources r = getResources();
if(signalStrength.isGsm()){
val = signalStrength.getGsmSignalStrength()*2-111 + " " + r.getString(R.string.base_info_display_dbm);
}else{
val = signalStrength.getCdmaDbm()*2-111 + " " + r.getString(R.string.base_info_display_dbm);
}
dbm.setText(val);
}
//小区状态
public void onCellLocationChanged(CellLocation location) {
Log.v(TAG, "onCellLocationChanged()");
updateLocation(location);
}
//服务状态
public void onServiceStateChanged(ServiceState serviceState) {
super.onServiceStateChanged(serviceState);
updateServiceState(serviceState);
}
//数据连接状态
public void onDataConnectionStateChanged(int state) {
updateDataState();//gprs
updateDataStats(); //
updateNetworkType();//network
};
//消息等待
public void onMessageWaitingIndicatorChanged(boolean mwi) {
mMwiValue = mwi;
updateMessageWaiting();
};
//呼叫重定向
public void onCallForwardingIndicatorChanged(boolean cfi) {
mCfiValue = cfi;
updateCallRedirect();
};
//呼叫状态
public void onCallStateChanged(int state, String incomingNumber) {
updatePhoneState(state,incomingNumber);
};
//PPP数据
public void onDataActivity(int direction) {
updateDataStats2();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
setContentView(R.layout.base_info);
mDeviceId = (TextView) findViewById(R.id.imei);
operatorName = (TextView)findViewById(R.id.operator);
gsmState = (TextView) findViewById(R.id.gsm);
roamingState = (TextView)findViewById(R.id.roaming);
pingTestButton = (Button)findViewById(R.id.ping_test);
pingTestButton.setOnClickListener(mPingButtonHandler);
mPingIpAddr = (TextView) findViewById(R.id.pingIpAddr);
mPingHostname = (TextView) findViewById(R.id.pingHostname);
mHttpClientTest = (TextView) findViewById(R.id.httpClientTest);
dbm = (TextView)findViewById(R.id.dbm);
//TODO---ASU
asu = (TextView)findViewById(R.id.asu);
mLocation = (TextView)findViewById(R.id.location);
mNeighboringCids = (TextView) findViewById(R.id.neighboring);
mLockLacCid = (Button)findViewById(R.id.lockLacCid);
mLockLacCid.setOnClickListener(mLockButtonHandler);
gprsState = (TextView)findViewById(R.id.gprs);
network = (TextView)findViewById(R.id.network);
mMwi = (TextView)findViewById(R.id.mwi);
mCfi = (TextView)findViewById(R.id.cfi);
callState = (TextView)findViewById(R.id.call);
resets = (TextView)findViewById(R.id.resets);
attempts = (TextView)findViewById(R.id.attempts);
successes = (TextView)findViewById(R.id.successes);
sent = (TextView)findViewById(R.id.sent);
received = (TextView)findViewById(R.id.received);
sentSinceReceived = (TextView)findViewById(R.id.sentSinceReceived);
preferredNetworkType = (Spinner)findViewById(R.id.preferredNetworkType);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mPreferredNetworkLabels);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
preferredNetworkType.setAdapter(adapter);
// preferredNetworkType.setOnItemSelectedListener(mPreferredNetworkHandler);
oemInfoButton = (Button) findViewById(R.id.oem_info);
oemInfoButton.setOnClickListener(mOemInfoButtonHandler);
PackageManager pm = getPackageManager();
Intent oemInfoIntent = new Intent("com.android.settings.OEM_RADIO_INFO");
List<ResolveInfo> oemInfoIntentList = pm.queryIntentActivities(oemInfoIntent, 0);
if(oemInfoIntentList.size() == 0){
oemInfoButton.setEnabled(false);
}
// CellLocation.requestLocationUpdate();
//放在这里,不放在onResume()方法里,广播注册一样,地址改变了会发送广播给监听了这个信息的类接收,下面就监听了
// CellLocation.requestLocationUpdate();
}
@Override
protected void onResume() {
super.onResume();
updateProperties();
updateNeighboringCids(mTelephonyManager);
mTelephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
| PhoneStateListener.LISTEN_SERVICE_STATE
| PhoneStateListener.LISTEN_CELL_LOCATION
| PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
| PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR
| PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
| PhoneStateListener.LISTEN_CALL_STATE
| PhoneStateListener.LISTEN_DATA_ACTIVITY);
}
@Override
protected void onPause() {
super.onPause();
if(mTimer != null)
mTimer.cancel();
}
// 锁屏按钮
OnClickListener mLockButtonHandler = new OnClickListener() {
@Override
public void onClick(View v) {
// CellLocation cellLocation = mTelephonyManager.getCellLocation();
// GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
// Bundle m = new Bundle();
// m.putInt("lac", -1);
// m.putInt("cid", -1);
// m.putInt("psc", gsmCellLocation.getPsc());
// gsmCellLocation.fillInNotifierBundle(m);
// gsmCellLocation.setLacAndCid(-1, -1);
// CellLocation.requestLocationUpdate();
List<NeighboringCellInfo> cellList = mTelephonyManager.getNeighboringCellInfo();
int size = cellList.size();
final String[] items = new String[size];
NeighboringCellInfo cell;
for(int i = 0; i < size; i++){
cell = cellList.get(i);
items[i] = cell.getLac() + " & " + cell.getCid();
}
AlertDialog.Builder builder = new AlertDialog.Builder(BaseInfoActivity.this);
String title = mRes.getString(R.string.neighbor_dialog_title);
builder.setTitle(title)
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CellLocation cellLocation = mTelephonyManager.getCellLocation();
String[] item = items[which].split("&");
int lac = Integer.valueOf(item[0].trim());
int cid = Integer.valueOf(item[1].trim());
if(cellLocation instanceof GsmCellLocation){
GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
// gsmCellLocation.setStateInvalid();
gsmCellLocation.setLacAndCid(-1,-1);
CellLocation.requestLocationUpdate();
Toast.makeText(BaseInfoActivity.this, "设置成功 lac:"+lac+",cid:"+cid, 3000).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
};
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
};
};
//
AdapterView.OnItemSelectedListener mPreferredNetworkHandler = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// Message msg = mHandler.obtainMessage();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
};
//Oem按钮Handler
OnClickListener mOemInfoButtonHandler = new OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent("com.android.settings.OEM_RADIO_INFO");
try{
startActivity(intent);
}catch(android.content.ActivityNotFoundException ex){
Log.d(TAG,"OEM-specific Info/Settings Activity Not Found : " + ex);
}
}
};
private final void updateDataStats2(){
Resources r = getResources();
long txPackets = TrafficStats.getMobileTxPackets();
long rxPackets = TrafficStats.getMobileRxPackets();
long txBytes = TrafficStats.getMobileTxBytes();
long rxBytes = TrafficStats.getMobileRxBytes();
String packets = r.getString(R.string.base_info_display_packets);
String bytes = r.getString(R.string.base_info_display_bytes);
sent.setText(txPackets + " " + packets + ", " + txBytes + " " + bytes);
received.setText(rxPackets + " " + packets + ", " + rxBytes + " " + bytes);
}
/*
* 更新无线通信重置 数据尝试次数 数据成功
*/
private final void updateDataStats(){
Object obj;
try {
Class<?> sys = Class.forName("android.os.SystemProperties");
Method method = sys.getMethod("get", String.class,String.class);
//静态方法,则不需要构造实例的方式了
obj = method.invoke(sys, "net.gsm.radio-reset","0");
resets.setText(obj.toString());
obj = method.invoke(sys, "net.gsm.attempt-gprs","0");
attempts.setText(obj.toString());
obj = method.invoke(sys, "net.ppp.reset-by-timeout","0");
successes.setText(obj.toString());
obj = method.invoke(sys, "net.ppp.reset-by-timeout","0");
sentSinceReceived.setText(obj.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 更新呼叫状态
* @param state
* @param incomingNumber
*/
private final void updatePhoneState(int state, String incomingNumber){
String display = mRes.getString(R.string.base_info_unknown);
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
display = mRes.getString(R.string.base_info_phone_idle);
break;
case TelephonyManager.CALL_STATE_RINGING:
display = mRes.getString(R.string.base_info_phone_ringing);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
display = mRes.getString(R.string.base_info_phone_offhook);
break;
}
callState.setText(display);
}
/**
* 更新呼叫重定向
*/
private final void updateCallRedirect(){
mCfi.setText(String.valueOf(mCfiValue));
}
/**
* 更新消息等待
*/
private final void updateMessageWaiting(){
mMwi.setText(String.valueOf(mMwiValue));
}
/**
* 更新网络类型
*/
private final void updateNetworkType(){
int networkType = mTelephonyManager.getNetworkType();
String display = mRes.getString(R.string.base_info_unknown);
switch(networkType){
case TelephonyManager.NETWORK_TYPE_CDMA:
display = mRes.getString(R.string.base_info_network_type_cdma);
break;
case TelephonyManager.NETWORK_TYPE_EDGE:
display = mRes.getString(R.string.base_info_network_type_edge);
break;
case TelephonyManager.NETWORK_TYPE_GPRS:
display = mRes.getString(R.string.base_info_network_type_gprs);
break;
case TelephonyManager.NETWORK_TYPE_EVDO_0:
display = mRes.getString(R.string.base_info_network_type_evdo_0);
break;
case TelephonyManager.NETWORK_TYPE_EVDO_A:
display = mRes.getString(R.string.base_info_network_type_evdo_A);
break;
case TelephonyManager.NETWORK_TYPE_EVDO_B:
display = mRes.getString(R.string.base_info_network_type_evdo_B);
break;
}
network.setText(display);
}
/**
* 更新Gprs状态
*/
private final void updateDataState(){
int state = mTelephonyManager.getDataState();
String display = mRes.getString(R.string.base_info_unknown);
switch(state){
case TelephonyManager.DATA_CONNECTED:
display = mRes.getString(R.string.base_info_data_connected);
break;
case TelephonyManager.DATA_CONNECTING:
display = mRes.getString(R.string.base_info_data_connecting);
break;
case TelephonyManager.DATA_DISCONNECTED:
display = mRes.getString(R.string.base_info_data_suspended);
break;
}
gprsState.setText(display);
}
Timer mTimer ;
final StringBuilder sb = new StringBuilder();
final Handler handler = new Handler();
/**
* 更新邻小区
* @param tm
*/
private final void updateNeighboringCids(TelephonyManager tm){
final TelephonyManager telephony = tm;
final Runnable updateNeiCids = new Runnable(){
@Override
public void run() {
mNeighboringCids.setText(sb.toString());
}
};
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
List<NeighboringCellInfo> cellList = telephony.getNeighboringCellInfo();
// Toast.makeText(BaseInfoActivity.this, "size" + cellList.size(), 1000).show();
sb.delete(0, sb.length());
for(NeighboringCellInfo ci : cellList){
sb.append("LAC:").append(ci.getLac()).append(",CID:").append(ci.getCid()).append("\n");
}
handler.post(updateNeiCids);
}
}, 0, 3000);
}
/**
* 更新主小区地区信息 LAC CID
* @param location
*/
private final void updateLocation(CellLocation location){
if(location instanceof GsmCellLocation){
GsmCellLocation loc = (GsmCellLocation)location;
int lac = loc.getLac();
int cid = loc.getCid();
mLocation.setText(mRes.getString(R.string.base_info_lac) + " = "
+ ((lac == -1) ? "unknown" : lac)
+ " "
+ mRes.getString(R.string.base_info_cid) + " = "
+ ((cid == -1) ? "unknown" : cid));
}else if(location instanceof CdmaCellLocation){
CdmaCellLocation loc = (CdmaCellLocation)location;
int bid = loc.getBaseStationId();
int sid = loc.getSystemId();
int nid = loc.getNetworkId();
int lat = loc.getBaseStationLatitude();
int lon = loc.getBaseStationLongitude();
mLocation.setText("BID = "
+ ((bid == -1) ? "unknown" : Integer.toHexString(bid))
+ " "
+ "SID = "
+ ((sid == -1) ? "unknown" : Integer.toHexString(sid))
+ "NID = "
+ ((nid == -1) ? "unknown" : Integer.toHexString(nid))
+ "\n"
+ "LAT = "
+ ((lat == -1) ? "unknown" : Integer.toHexString(lat))
+ " "
+ "LONG = "
+ ((lon == -1) ? "unknown" : Integer.toHexString(lon)));
}else{
mLocation.setTag("unknown");
}
}
//Ping Button
OnClickListener mPingButtonHandler = new OnClickListener() {
@Override
public void onClick(View v) {
updatePingState();
}
};
/**
* 更新Ping有关的状态
*/
private final void updatePingState() {
// final Handler handler = new Handler();
// Set all to unknown since the threads will take a few secs to update.
mPingIpAddrResult = mRes.getString(R.string.base_info_unknown);
mPingHostnameResult = mRes.getString(R.string.base_info_unknown);
mHttpClientTestResult = mRes.getString(R.string.base_info_unknown);
mPingIpAddr.setText(mPingIpAddrResult);
mPingHostname.setText(mPingHostnameResult);
mHttpClientTest.setText(mHttpClientTestResult);
final Runnable updatePingResults = new Runnable(){
public void run() {
mPingIpAddr.setText(mPingIpAddrResult);
mPingHostname.setText(mPingHostnameResult);
mHttpClientTest.setText(mHttpClientTestResult);
}
};
Thread ipAddr = new Thread(){
@Override
public void run() {
pingIpAddr();
handler.post(updatePingResults);
}
};
ipAddr.start();
Thread hostname = new Thread(){
public void run() {
pingHostname();
handler.post(updatePingResults);
}
};
hostname.start();
Thread httpClient = new Thread(){
public void run() {
httpClientTest();
handler.post(updatePingResults);
}
};
httpClient.start();
}
/**
* HttpClient测试
*/
private void httpClientTest(){
HttpClient client = new DefaultHttpClient();
try {
HttpGet request = new HttpGet("http://www.baidu.com/");
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
mHttpClientTestResult = "Pass";
}else{
mHttpClientTestResult = "Fail: Code " + String.valueOf(response);
}
request.abort();
} catch (IOException e) {
mHttpClientTestResult = "Fail: IOException";
e.printStackTrace();
}finally{
client.getConnectionManager().shutdown();
}
}
/**
* 主机地址测试(移动网络可行 wifi不行)
*/
private final void pingHostname(){
try {
Process p = Runtime.getRuntime().exec("ping -c 1 www.baidu.com");
int status = p.waitFor();
if(status == 0){
mPingHostnameResult = "Pass";
}else{
mPingHostnameResult = "Fail: Host unreachable";
}
} catch (IOException e) {
mPingHostnameResult = "Fail:IOException";
} catch (InterruptedException e) {
mPingHostnameResult = "Fail: Host unreachable";
}
};
/**
* Ip地址测试(移动网络可行 wifi不行)
*/
private final void pingIpAddr(){
try {
String ipAddress = "220.181.111.86";//baidu.com
Process p = Runtime.getRuntime().exec("ping -c 1 " + ipAddress);
int status = p.waitFor();
if(status == 0){
mPingIpAddrResult = "Pass";
}else{
mPingIpAddrResult = "Fail: IP addr not reachable";
}
} catch (IOException e) {
mPingIpAddrResult = "Fail: IOException";
} catch (InterruptedException e) {
mPingIpAddrResult = "Fail: InterruptedException";
}
}
private void updateProperties() {
String lineNumber = mTelephonyManager.getLine1Number();
String s = mTelephonyManager.getDeviceId();
mDeviceId.setText(s + ":" + lineNumber);
}
private void updateServiceState(ServiceState serviceState) {
int state = serviceState.getState();
String display = mRes.getString(R.string.base_info_unknown);
switch(state){
case ServiceState.STATE_IN_SERVICE:
display = mRes.getString(R.string.base_info_service_in);
break;
case ServiceState.STATE_OUT_OF_SERVICE:
case ServiceState.STATE_EMERGENCY_ONLY:
display = mRes.getString(R.string.base_info_service_emergency);
break;
case ServiceState.STATE_POWER_OFF:
display = mRes.getString(R.string.base_info_service_off);
break;
}
gsmState.setText(display);
if(serviceState.getRoaming()){
roamingState.setText(R.string.base_Info_roaming_in);
}else{
roamingState.setText(R.string.base_Info_roaming_not);
}
operatorName.setText(serviceState.getOperatorAlphaLong());
}
private String[] mPreferredNetworkLabels = {
"WCDMA preferred",
"GSM only",
"WCDMA only",
"GSM auto (PRL)",
"CDMA auto (PRL)",
"CDMA only",
"EvDo only",
"GSM/CDMA auto (PRL)",
"Unknown"};
}
| zzx-project-work | rms/src/com/asd/rms/BaseInfoActivity.java | Java | gpl3 | 22,218 |
package com.asd.rms;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.widget.TabHost;
import android.widget.TextView;
public class RmsActivity extends TabActivity {
TabHost mTabHost;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab1")
.setIndicator("基本信息")
.setContent(new Intent(this,BaseInfoActivity.class)));
}
} | zzx-project-work | rms/src/com/asd/rms/RmsActivity.java | Java | gpl3 | 641 |
/*
* i386 specific functions for TCC assembler
*
* Copyright (c) 2001, 2002 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define MAX_OPERANDS 3
typedef struct ASMInstr {
uint16_t sym;
uint16_t opcode;
uint16_t instr_type;
#define OPC_JMP 0x01 /* jmp operand */
#define OPC_B 0x02 /* only used zith OPC_WL */
#define OPC_WL 0x04 /* accepts w, l or no suffix */
#define OPC_BWL (OPC_B | OPC_WL) /* accepts b, w, l or no suffix */
#define OPC_REG 0x08 /* register is added to opcode */
#define OPC_MODRM 0x10 /* modrm encoding */
#define OPC_FWAIT 0x20 /* add fwait opcode */
#define OPC_TEST 0x40 /* test opcodes */
#define OPC_SHIFT 0x80 /* shift opcodes */
#define OPC_D16 0x0100 /* generate data16 prefix */
#define OPC_ARITH 0x0200 /* arithmetic opcodes */
#define OPC_SHORTJMP 0x0400 /* short jmp operand */
#define OPC_FARITH 0x0800 /* FPU arithmetic opcodes */
#define OPC_GROUP_SHIFT 13
/* in order to compress the operand type, we use specific operands and
we or only with EA */
#define OPT_REG8 0 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_REG16 1 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_REG32 2 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_MMX 3 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_SSE 4 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_CR 5 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_TR 6 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_DB 7 /* warning: value is hardcoded from TOK_ASM_xxx */
#define OPT_SEG 8
#define OPT_ST 9
#define OPT_IM8 10
#define OPT_IM8S 11
#define OPT_IM16 12
#define OPT_IM32 13
#define OPT_EAX 14 /* %al, %ax or %eax register */
#define OPT_ST0 15 /* %st(0) register */
#define OPT_CL 16 /* %cl register */
#define OPT_DX 17 /* %dx register */
#define OPT_ADDR 18 /* OP_EA with only offset */
#define OPT_INDIR 19 /* *(expr) */
/* composite types */
#define OPT_COMPOSITE_FIRST 20
#define OPT_IM 20 /* IM8 | IM16 | IM32 */
#define OPT_REG 21 /* REG8 | REG16 | REG32 */
#define OPT_REGW 22 /* REG16 | REG32 */
#define OPT_IMW 23 /* IM16 | IM32 */
/* can be ored with any OPT_xxx */
#define OPT_EA 0x80
uint8_t nb_ops;
uint8_t op_type[MAX_OPERANDS]; /* see OP_xxx */
} ASMInstr;
typedef struct Operand {
uint32_t type;
#define OP_REG8 (1 << OPT_REG8)
#define OP_REG16 (1 << OPT_REG16)
#define OP_REG32 (1 << OPT_REG32)
#define OP_MMX (1 << OPT_MMX)
#define OP_SSE (1 << OPT_SSE)
#define OP_CR (1 << OPT_CR)
#define OP_TR (1 << OPT_TR)
#define OP_DB (1 << OPT_DB)
#define OP_SEG (1 << OPT_SEG)
#define OP_ST (1 << OPT_ST)
#define OP_IM8 (1 << OPT_IM8)
#define OP_IM8S (1 << OPT_IM8S)
#define OP_IM16 (1 << OPT_IM16)
#define OP_IM32 (1 << OPT_IM32)
#define OP_EAX (1 << OPT_EAX)
#define OP_ST0 (1 << OPT_ST0)
#define OP_CL (1 << OPT_CL)
#define OP_DX (1 << OPT_DX)
#define OP_ADDR (1 << OPT_ADDR)
#define OP_INDIR (1 << OPT_INDIR)
#define OP_EA 0x40000000
#define OP_REG (OP_REG8 | OP_REG16 | OP_REG32)
#define OP_IM OP_IM32
int8_t reg; /* register, -1 if none */
int8_t reg2; /* second register, -1 if none */
uint8_t shift;
ExprValue e;
} Operand;
static const uint8_t reg_to_size[5] = {
/*
[OP_REG8] = 0,
[OP_REG16] = 1,
[OP_REG32] = 2,
*/
0, 0, 1, 0, 2
};
#define WORD_PREFIX_OPCODE 0x66
#define NB_TEST_OPCODES 30
static const uint8_t test_bits[NB_TEST_OPCODES] = {
0x00, /* o */
0x01, /* no */
0x02, /* b */
0x02, /* c */
0x02, /* nae */
0x03, /* nb */
0x03, /* nc */
0x03, /* ae */
0x04, /* e */
0x04, /* z */
0x05, /* ne */
0x05, /* nz */
0x06, /* be */
0x06, /* na */
0x07, /* nbe */
0x07, /* a */
0x08, /* s */
0x09, /* ns */
0x0a, /* p */
0x0a, /* pe */
0x0b, /* np */
0x0b, /* po */
0x0c, /* l */
0x0c, /* nge */
0x0d, /* nl */
0x0d, /* ge */
0x0e, /* le */
0x0e, /* ng */
0x0f, /* nle */
0x0f, /* g */
};
static const uint8_t segment_prefixes[] = {
0x26, /* es */
0x2e, /* cs */
0x36, /* ss */
0x3e, /* ds */
0x64, /* fs */
0x65 /* gs */
};
static const ASMInstr asm_instrs[] = {
#define ALT(x) x
#define DEF_ASM_OP0(name, opcode)
#define DEF_ASM_OP0L(name, opcode, group, instr_type) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 0 },
#define DEF_ASM_OP1(name, opcode, group, instr_type, op0) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 1, { op0 }},
#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 2, { op0, op1 }},
#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 3, { op0, op1, op2 }},
#include "i386-asm.h"
/* last operation */
{ 0, },
};
static const uint16_t op0_codes[] = {
#define ALT(x)
#define DEF_ASM_OP0(x, opcode) opcode,
#define DEF_ASM_OP0L(name, opcode, group, instr_type)
#define DEF_ASM_OP1(name, opcode, group, instr_type, op0)
#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1)
#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2)
#include "i386-asm.h"
};
static inline int get_reg_shift(TCCState *s1)
{
int shift, v;
v = asm_int_expr(s1);
switch(v) {
case 1:
shift = 0;
break;
case 2:
shift = 1;
break;
case 4:
shift = 2;
break;
case 8:
shift = 3;
break;
default:
expect("1, 2, 4 or 8 constant");
shift = 0;
break;
}
return shift;
}
static int asm_parse_reg(void)
{
int reg;
if (tok != '%')
goto error_32;
next();
if (tok >= TOK_ASM_eax && tok <= TOK_ASM_edi) {
reg = tok - TOK_ASM_eax;
next();
return reg;
} else {
error_32:
expect("32 bit register");
return 0;
}
}
static void parse_operand(TCCState *s1, Operand *op)
{
ExprValue e;
int reg, indir;
const char *p;
indir = 0;
if (tok == '*') {
next();
indir = OP_INDIR;
}
if (tok == '%') {
next();
if (tok >= TOK_ASM_al && tok <= TOK_ASM_db7) {
reg = tok - TOK_ASM_al;
op->type = 1 << (reg >> 3); /* WARNING: do not change constant order */
op->reg = reg & 7;
if ((op->type & OP_REG) && op->reg == TREG_EAX)
op->type |= OP_EAX;
else if (op->type == OP_REG8 && op->reg == TREG_ECX)
op->type |= OP_CL;
else if (op->type == OP_REG16 && op->reg == TREG_EDX)
op->type |= OP_DX;
} else if (tok >= TOK_ASM_dr0 && tok <= TOK_ASM_dr7) {
op->type = OP_DB;
op->reg = tok - TOK_ASM_dr0;
} else if (tok >= TOK_ASM_es && tok <= TOK_ASM_gs) {
op->type = OP_SEG;
op->reg = tok - TOK_ASM_es;
} else if (tok == TOK_ASM_st) {
op->type = OP_ST;
op->reg = 0;
next();
if (tok == '(') {
next();
if (tok != TOK_PPNUM)
goto reg_error;
p = tokc.cstr->data;
reg = p[0] - '0';
if ((unsigned)reg >= 8 || p[1] != '\0')
goto reg_error;
op->reg = reg;
next();
skip(')');
}
if (op->reg == 0)
op->type |= OP_ST0;
goto no_skip;
} else {
reg_error:
error("unknown register");
}
next();
no_skip: ;
} else if (tok == '$') {
/* constant value */
next();
asm_expr(s1, &e);
op->type = OP_IM32;
op->e.v = e.v;
op->e.sym = e.sym;
if (!op->e.sym) {
if (op->e.v == (uint8_t)op->e.v)
op->type |= OP_IM8;
if (op->e.v == (int8_t)op->e.v)
op->type |= OP_IM8S;
if (op->e.v == (uint16_t)op->e.v)
op->type |= OP_IM16;
}
} else {
/* address(reg,reg2,shift) with all variants */
op->type = OP_EA;
op->reg = -1;
op->reg2 = -1;
op->shift = 0;
if (tok != '(') {
asm_expr(s1, &e);
op->e.v = e.v;
op->e.sym = e.sym;
} else {
op->e.v = 0;
op->e.sym = NULL;
}
if (tok == '(') {
next();
if (tok != ',') {
op->reg = asm_parse_reg();
}
if (tok == ',') {
next();
if (tok != ',') {
op->reg2 = asm_parse_reg();
}
if (tok == ',') {
next();
op->shift = get_reg_shift(s1);
}
}
skip(')');
}
if (op->reg == -1 && op->reg2 == -1)
op->type |= OP_ADDR;
}
op->type |= indir;
}
/* XXX: unify with C code output ? */
static void gen_expr32(ExprValue *pe)
{
if (pe->sym)
greloc(cur_text_section, pe->sym, ind, R_386_32);
gen_le32(pe->v);
}
/* XXX: unify with C code output ? */
static void gen_disp32(ExprValue *pe)
{
Sym *sym;
sym = pe->sym;
if (sym) {
if (sym->r == cur_text_section->sh_num) {
/* same section: we can output an absolute value. Note
that the TCC compiler behaves differently here because
it always outputs a relocation to ease (future) code
elimination in the linker */
gen_le32(pe->v + (long)sym->next - ind - 4);
} else {
greloc(cur_text_section, sym, ind, R_386_PC32);
gen_le32(pe->v - 4);
}
} else {
/* put an empty PC32 relocation */
put_elf_reloc(symtab_section, cur_text_section,
ind, R_386_PC32, 0);
gen_le32(pe->v - 4);
}
}
static void gen_le16(int v)
{
g(v);
g(v >> 8);
}
/* generate the modrm operand */
static inline void asm_modrm(int reg, Operand *op)
{
int mod, reg1, reg2, sib_reg1;
if (op->type & (OP_REG | OP_MMX | OP_SSE)) {
g(0xc0 + (reg << 3) + op->reg);
} else if (op->reg == -1 && op->reg2 == -1) {
/* displacement only */
g(0x05 + (reg << 3));
gen_expr32(&op->e);
} else {
sib_reg1 = op->reg;
/* fist compute displacement encoding */
if (sib_reg1 == -1) {
sib_reg1 = 5;
mod = 0x00;
} else if (op->e.v == 0 && !op->e.sym && op->reg != 5) {
mod = 0x00;
} else if (op->e.v == (int8_t)op->e.v && !op->e.sym) {
mod = 0x40;
} else {
mod = 0x80;
}
/* compute if sib byte needed */
reg1 = op->reg;
if (op->reg2 != -1)
reg1 = 4;
g(mod + (reg << 3) + reg1);
if (reg1 == 4) {
/* add sib byte */
reg2 = op->reg2;
if (reg2 == -1)
reg2 = 4; /* indicate no index */
g((op->shift << 6) + (reg2 << 3) + sib_reg1);
}
/* add offset */
if (mod == 0x40) {
g(op->e.v);
} else if (mod == 0x80 || op->reg == -1) {
gen_expr32(&op->e);
}
}
}
static void asm_opcode(TCCState *s1, int opcode)
{
const ASMInstr *pa;
int i, modrm_index, reg, v, op1, is_short_jmp, seg_prefix;
int nb_ops, s, ss;
Operand ops[MAX_OPERANDS], *pop;
int op_type[3]; /* decoded op type */
/* get operands */
pop = ops;
nb_ops = 0;
seg_prefix = 0;
for(;;) {
if (tok == ';' || tok == TOK_LINEFEED)
break;
if (nb_ops >= MAX_OPERANDS) {
error("incorrect number of operands");
}
parse_operand(s1, pop);
if (tok == ':') {
if (pop->type != OP_SEG || seg_prefix) {
error("incorrect prefix");
}
seg_prefix = segment_prefixes[pop->reg];
next();
parse_operand(s1, pop);
if (!(pop->type & OP_EA)) {
error("segment prefix must be followed by memory reference");
}
}
pop++;
nb_ops++;
if (tok != ',')
break;
next();
}
is_short_jmp = 0;
s = 0; /* avoid warning */
/* optimize matching by using a lookup table (no hashing is needed
!) */
for(pa = asm_instrs; pa->sym != 0; pa++) {
s = 0;
if (pa->instr_type & OPC_FARITH) {
v = opcode - pa->sym;
if (!((unsigned)v < 8 * 6 && (v % 6) == 0))
continue;
} else if (pa->instr_type & OPC_ARITH) {
if (!(opcode >= pa->sym && opcode < pa->sym + 8 * 4))
continue;
goto compute_size;
} else if (pa->instr_type & OPC_SHIFT) {
if (!(opcode >= pa->sym && opcode < pa->sym + 7 * 4))
continue;
goto compute_size;
} else if (pa->instr_type & OPC_TEST) {
if (!(opcode >= pa->sym && opcode < pa->sym + NB_TEST_OPCODES))
continue;
} else if (pa->instr_type & OPC_B) {
if (!(opcode >= pa->sym && opcode <= pa->sym + 3))
continue;
compute_size:
s = (opcode - pa->sym) & 3;
} else if (pa->instr_type & OPC_WL) {
if (!(opcode >= pa->sym && opcode <= pa->sym + 2))
continue;
s = opcode - pa->sym + 1;
} else {
if (pa->sym != opcode)
continue;
}
if (pa->nb_ops != nb_ops)
continue;
/* now decode and check each operand */
for(i = 0; i < nb_ops; i++) {
int op1, op2;
op1 = pa->op_type[i];
op2 = op1 & 0x1f;
switch(op2) {
case OPT_IM:
v = OP_IM8 | OP_IM16 | OP_IM32;
break;
case OPT_REG:
v = OP_REG8 | OP_REG16 | OP_REG32;
break;
case OPT_REGW:
v = OP_REG16 | OP_REG32;
break;
case OPT_IMW:
v = OP_IM16 | OP_IM32;
break;
default:
v = 1 << op2;
break;
}
if (op1 & OPT_EA)
v |= OP_EA;
op_type[i] = v;
if ((ops[i].type & v) == 0)
goto next;
}
/* all is matching ! */
break;
next: ;
}
if (pa->sym == 0) {
if (opcode >= TOK_ASM_pusha && opcode <= TOK_ASM_emms) {
int b;
b = op0_codes[opcode - TOK_ASM_pusha];
if (b & 0xff00)
g(b >> 8);
g(b);
return;
} else {
error("unknown opcode '%s'",
get_tok_str(opcode, NULL));
}
}
/* if the size is unknown, then evaluate it (OPC_B or OPC_WL case) */
if (s == 3) {
for(i = 0; s == 3 && i < nb_ops; i++) {
if ((ops[i].type & OP_REG) && !(op_type[i] & (OP_CL | OP_DX)))
s = reg_to_size[ops[i].type & OP_REG];
}
if (s == 3) {
if ((opcode == TOK_ASM_push || opcode == TOK_ASM_pop) &&
(ops[0].type & (OP_SEG | OP_IM8S | OP_IM32)))
s = 2;
else
error("cannot infer opcode suffix");
}
}
/* generate data16 prefix if needed */
ss = s;
if (s == 1 || (pa->instr_type & OPC_D16))
g(WORD_PREFIX_OPCODE);
else if (s == 2)
s = 1;
/* now generates the operation */
if (pa->instr_type & OPC_FWAIT)
g(0x9b);
if (seg_prefix)
g(seg_prefix);
v = pa->opcode;
if (v == 0x69 || v == 0x69) {
/* kludge for imul $im, %reg */
nb_ops = 3;
ops[2] = ops[1];
} else if (v == 0xcd && ops[0].e.v == 3 && !ops[0].e.sym) {
v--; /* int $3 case */
nb_ops = 0;
} else if ((v == 0x06 || v == 0x07)) {
if (ops[0].reg >= 4) {
/* push/pop %fs or %gs */
v = 0x0fa0 + (v - 0x06) + ((ops[0].reg - 4) << 3);
} else {
v += ops[0].reg << 3;
}
nb_ops = 0;
} else if (v <= 0x05) {
/* arith case */
v += ((opcode - TOK_ASM_addb) >> 2) << 3;
} else if ((pa->instr_type & (OPC_FARITH | OPC_MODRM)) == OPC_FARITH) {
/* fpu arith case */
v += ((opcode - pa->sym) / 6) << 3;
}
if (pa->instr_type & OPC_REG) {
for(i = 0; i < nb_ops; i++) {
if (op_type[i] & (OP_REG | OP_ST)) {
v += ops[i].reg;
break;
}
}
/* mov $im, %reg case */
if (pa->opcode == 0xb0 && s >= 1)
v += 7;
}
if (pa->instr_type & OPC_B)
v += s;
if (pa->instr_type & OPC_TEST)
v += test_bits[opcode - pa->sym];
if (pa->instr_type & OPC_SHORTJMP) {
Sym *sym;
int jmp_disp;
/* see if we can really generate the jump with a byte offset */
sym = ops[0].e.sym;
if (!sym)
goto no_short_jump;
if (sym->r != cur_text_section->sh_num)
goto no_short_jump;
jmp_disp = ops[0].e.v + (long)sym->next - ind - 2;
if (jmp_disp == (int8_t)jmp_disp) {
/* OK to generate jump */
is_short_jmp = 1;
ops[0].e.v = jmp_disp;
} else {
no_short_jump:
if (pa->instr_type & OPC_JMP) {
/* long jump will be allowed. need to modify the
opcode slightly */
if (v == 0xeb)
v = 0xe9;
else
v += 0x0f10;
} else {
error("invalid displacement");
}
}
}
op1 = v >> 8;
if (op1)
g(op1);
g(v);
/* search which operand will used for modrm */
modrm_index = 0;
if (pa->instr_type & OPC_SHIFT) {
reg = (opcode - pa->sym) >> 2;
if (reg == 6)
reg = 7;
} else if (pa->instr_type & OPC_ARITH) {
reg = (opcode - pa->sym) >> 2;
} else if (pa->instr_type & OPC_FARITH) {
reg = (opcode - pa->sym) / 6;
} else {
reg = (pa->instr_type >> OPC_GROUP_SHIFT) & 7;
}
if (pa->instr_type & OPC_MODRM) {
/* first look for an ea operand */
for(i = 0;i < nb_ops; i++) {
if (op_type[i] & OP_EA)
goto modrm_found;
}
/* then if not found, a register or indirection (shift instructions) */
for(i = 0;i < nb_ops; i++) {
if (op_type[i] & (OP_REG | OP_MMX | OP_SSE | OP_INDIR))
goto modrm_found;
}
#ifdef ASM_DEBUG
error("bad op table");
#endif
modrm_found:
modrm_index = i;
/* if a register is used in another operand then it is
used instead of group */
for(i = 0;i < nb_ops; i++) {
v = op_type[i];
if (i != modrm_index &&
(v & (OP_REG | OP_MMX | OP_SSE | OP_CR | OP_TR | OP_DB | OP_SEG))) {
reg = ops[i].reg;
break;
}
}
asm_modrm(reg, &ops[modrm_index]);
}
/* emit constants */
if (pa->opcode == 0x9a || pa->opcode == 0xea) {
/* ljmp or lcall kludge */
gen_expr32(&ops[1].e);
if (ops[0].e.sym)
error("cannot relocate");
gen_le16(ops[0].e.v);
} else {
for(i = 0;i < nb_ops; i++) {
v = op_type[i];
if (v & (OP_IM8 | OP_IM16 | OP_IM32 | OP_IM8S | OP_ADDR)) {
/* if multiple sizes are given it means we must look
at the op size */
if (v == (OP_IM8 | OP_IM16 | OP_IM32) ||
v == (OP_IM16 | OP_IM32)) {
if (ss == 0)
v = OP_IM8;
else if (ss == 1)
v = OP_IM16;
else
v = OP_IM32;
}
if (v & (OP_IM8 | OP_IM8S)) {
if (ops[i].e.sym)
goto error_relocate;
g(ops[i].e.v);
} else if (v & OP_IM16) {
if (ops[i].e.sym) {
error_relocate:
error("cannot relocate");
}
gen_le16(ops[i].e.v);
} else {
if (pa->instr_type & (OPC_JMP | OPC_SHORTJMP)) {
if (is_short_jmp)
g(ops[i].e.v);
else
gen_disp32(&ops[i].e);
} else {
gen_expr32(&ops[i].e);
}
}
}
}
}
}
#define NB_SAVED_REGS 3
#define NB_ASM_REGS 8
/* return the constraint priority (we allocate first the lowest
numbered constraints) */
static inline int constraint_priority(const char *str)
{
int priority, c, pr;
/* we take the lowest priority */
priority = 0;
for(;;) {
c = *str;
if (c == '\0')
break;
str++;
switch(c) {
case 'A':
pr = 0;
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'S':
case 'D':
pr = 1;
break;
case 'q':
pr = 2;
break;
case 'r':
pr = 3;
break;
case 'N':
case 'M':
case 'I':
case 'i':
case 'm':
case 'g':
pr = 4;
break;
default:
error("unknown constraint '%c'", c);
pr = 0;
}
if (pr > priority)
priority = pr;
}
return priority;
}
static const char *skip_constraint_modifiers(const char *p)
{
while (*p == '=' || *p == '&' || *p == '+' || *p == '%')
p++;
return p;
}
#define REG_OUT_MASK 0x01
#define REG_IN_MASK 0x02
#define is_reg_allocated(reg) (regs_allocated[reg] & reg_mask)
static void asm_compute_constraints(ASMOperand *operands,
int nb_operands, int nb_outputs,
const uint8_t *clobber_regs,
int *pout_reg)
{
ASMOperand *op;
int sorted_op[MAX_ASM_OPERANDS];
int i, j, k, p1, p2, tmp, reg, c, reg_mask;
const char *str;
uint8_t regs_allocated[NB_ASM_REGS];
/* init fields */
for(i=0;i<nb_operands;i++) {
op = &operands[i];
op->input_index = -1;
op->ref_index = -1;
op->reg = -1;
op->is_memory = 0;
op->is_rw = 0;
}
/* compute constraint priority and evaluate references to output
constraints if input constraints */
for(i=0;i<nb_operands;i++) {
op = &operands[i];
str = op->constraint;
str = skip_constraint_modifiers(str);
if (isnum(*str) || *str == '[') {
/* this is a reference to another constraint */
k = find_constraint(operands, nb_operands, str, NULL);
if ((unsigned)k >= i || i < nb_outputs)
error("invalid reference in constraint %d ('%s')",
i, str);
op->ref_index = k;
if (operands[k].input_index >= 0)
error("cannot reference twice the same operand");
operands[k].input_index = i;
op->priority = 5;
} else {
op->priority = constraint_priority(str);
}
}
/* sort operands according to their priority */
for(i=0;i<nb_operands;i++)
sorted_op[i] = i;
for(i=0;i<nb_operands - 1;i++) {
for(j=i+1;j<nb_operands;j++) {
p1 = operands[sorted_op[i]].priority;
p2 = operands[sorted_op[j]].priority;
if (p2 < p1) {
tmp = sorted_op[i];
sorted_op[i] = sorted_op[j];
sorted_op[j] = tmp;
}
}
}
for(i = 0;i < NB_ASM_REGS; i++) {
if (clobber_regs[i])
regs_allocated[i] = REG_IN_MASK | REG_OUT_MASK;
else
regs_allocated[i] = 0;
}
/* esp cannot be used */
regs_allocated[4] = REG_IN_MASK | REG_OUT_MASK;
/* ebp cannot be used yet */
regs_allocated[5] = REG_IN_MASK | REG_OUT_MASK;
/* allocate registers and generate corresponding asm moves */
for(i=0;i<nb_operands;i++) {
j = sorted_op[i];
op = &operands[j];
str = op->constraint;
/* no need to allocate references */
if (op->ref_index >= 0)
continue;
/* select if register is used for output, input or both */
if (op->input_index >= 0) {
reg_mask = REG_IN_MASK | REG_OUT_MASK;
} else if (j < nb_outputs) {
reg_mask = REG_OUT_MASK;
} else {
reg_mask = REG_IN_MASK;
}
try_next:
c = *str++;
switch(c) {
case '=':
goto try_next;
case '+':
op->is_rw = 1;
/* FALL THRU */
case '&':
if (j >= nb_outputs)
error("'%c' modifier can only be applied to outputs", c);
reg_mask = REG_IN_MASK | REG_OUT_MASK;
goto try_next;
case 'A':
/* allocate both eax and edx */
if (is_reg_allocated(TREG_EAX) ||
is_reg_allocated(TREG_EDX))
goto try_next;
op->is_llong = 1;
op->reg = TREG_EAX;
regs_allocated[TREG_EAX] |= reg_mask;
regs_allocated[TREG_EDX] |= reg_mask;
break;
case 'a':
reg = TREG_EAX;
goto alloc_reg;
case 'b':
reg = 3;
goto alloc_reg;
case 'c':
reg = TREG_ECX;
goto alloc_reg;
case 'd':
reg = TREG_EDX;
goto alloc_reg;
case 'S':
reg = 6;
goto alloc_reg;
case 'D':
reg = 7;
alloc_reg:
if (is_reg_allocated(reg))
goto try_next;
goto reg_found;
case 'q':
/* eax, ebx, ecx or edx */
for(reg = 0; reg < 4; reg++) {
if (!is_reg_allocated(reg))
goto reg_found;
}
goto try_next;
case 'r':
/* any general register */
for(reg = 0; reg < 8; reg++) {
if (!is_reg_allocated(reg))
goto reg_found;
}
goto try_next;
reg_found:
/* now we can reload in the register */
op->is_llong = 0;
op->reg = reg;
regs_allocated[reg] |= reg_mask;
break;
case 'i':
if (!((op->vt->r & (VT_VALMASK | VT_LVAL)) == VT_CONST))
goto try_next;
break;
case 'I':
case 'N':
case 'M':
if (!((op->vt->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST))
goto try_next;
break;
case 'm':
case 'g':
/* nothing special to do because the operand is already in
memory, except if the pointer itself is stored in a
memory variable (VT_LLOCAL case) */
/* XXX: fix constant case */
/* if it is a reference to a memory zone, it must lie
in a register, so we reserve the register in the
input registers and a load will be generated
later */
if (j < nb_outputs || c == 'm') {
if ((op->vt->r & VT_VALMASK) == VT_LLOCAL) {
/* any general register */
for(reg = 0; reg < 8; reg++) {
if (!(regs_allocated[reg] & REG_IN_MASK))
goto reg_found1;
}
goto try_next;
reg_found1:
/* now we can reload in the register */
regs_allocated[reg] |= REG_IN_MASK;
op->reg = reg;
op->is_memory = 1;
}
}
break;
default:
error("asm constraint %d ('%s') could not be satisfied",
j, op->constraint);
break;
}
/* if a reference is present for that operand, we assign it too */
if (op->input_index >= 0) {
operands[op->input_index].reg = op->reg;
operands[op->input_index].is_llong = op->is_llong;
}
}
/* compute out_reg. It is used to store outputs registers to memory
locations references by pointers (VT_LLOCAL case) */
*pout_reg = -1;
for(i=0;i<nb_operands;i++) {
op = &operands[i];
if (op->reg >= 0 &&
(op->vt->r & VT_VALMASK) == VT_LLOCAL &&
!op->is_memory) {
for(reg = 0; reg < 8; reg++) {
if (!(regs_allocated[reg] & REG_OUT_MASK))
goto reg_found2;
}
error("could not find free output register for reloading");
reg_found2:
*pout_reg = reg;
break;
}
}
/* print sorted constraints */
#ifdef ASM_DEBUG
for(i=0;i<nb_operands;i++) {
j = sorted_op[i];
op = &operands[j];
printf("%%%d [%s]: \"%s\" r=0x%04x reg=%d\n",
j,
op->id ? get_tok_str(op->id, NULL) : "",
op->constraint,
op->vt->r,
op->reg);
}
if (*pout_reg >= 0)
printf("out_reg=%d\n", *pout_reg);
#endif
}
static void subst_asm_operand(CString *add_str,
SValue *sv, int modifier)
{
int r, reg, size, val;
char buf[64];
r = sv->r;
if ((r & VT_VALMASK) == VT_CONST) {
if (!(r & VT_LVAL) && modifier != 'c' && modifier != 'n')
cstr_ccat(add_str, '$');
if (r & VT_SYM) {
cstr_cat(add_str, get_tok_str(sv->sym->v, NULL));
if (sv->c.i != 0) {
cstr_ccat(add_str, '+');
} else {
return;
}
}
val = sv->c.i;
if (modifier == 'n')
val = -val;
snprintf(buf, sizeof(buf), "%d", sv->c.i);
cstr_cat(add_str, buf);
} else if ((r & VT_VALMASK) == VT_LOCAL) {
snprintf(buf, sizeof(buf), "%d(%%ebp)", sv->c.i);
cstr_cat(add_str, buf);
} else if (r & VT_LVAL) {
reg = r & VT_VALMASK;
if (reg >= VT_CONST)
error("internal compiler error");
snprintf(buf, sizeof(buf), "(%%%s)",
get_tok_str(TOK_ASM_eax + reg, NULL));
cstr_cat(add_str, buf);
} else {
/* register case */
reg = r & VT_VALMASK;
if (reg >= VT_CONST)
error("internal compiler error");
/* choose register operand size */
if ((sv->type.t & VT_BTYPE) == VT_BYTE)
size = 1;
else if ((sv->type.t & VT_BTYPE) == VT_SHORT)
size = 2;
else
size = 4;
if (size == 1 && reg >= 4)
size = 4;
if (modifier == 'b') {
if (reg >= 4)
error("cannot use byte register");
size = 1;
} else if (modifier == 'h') {
if (reg >= 4)
error("cannot use byte register");
size = -1;
} else if (modifier == 'w') {
size = 2;
}
switch(size) {
case -1:
reg = TOK_ASM_ah + reg;
break;
case 1:
reg = TOK_ASM_al + reg;
break;
case 2:
reg = TOK_ASM_ax + reg;
break;
default:
reg = TOK_ASM_eax + reg;
break;
}
snprintf(buf, sizeof(buf), "%%%s", get_tok_str(reg, NULL));
cstr_cat(add_str, buf);
}
}
/* generate prolog and epilog code for asm statment */
static void asm_gen_code(ASMOperand *operands, int nb_operands,
int nb_outputs, int is_output,
uint8_t *clobber_regs,
int out_reg)
{
uint8_t regs_allocated[NB_ASM_REGS];
ASMOperand *op;
int i, reg;
static uint8_t reg_saved[NB_SAVED_REGS] = { 3, 6, 7 };
/* mark all used registers */
memcpy(regs_allocated, clobber_regs, sizeof(regs_allocated));
for(i = 0; i < nb_operands;i++) {
op = &operands[i];
if (op->reg >= 0)
regs_allocated[op->reg] = 1;
}
if (!is_output) {
/* generate reg save code */
for(i = 0; i < NB_SAVED_REGS; i++) {
reg = reg_saved[i];
if (regs_allocated[reg])
g(0x50 + reg);
}
/* generate load code */
for(i = 0; i < nb_operands; i++) {
op = &operands[i];
if (op->reg >= 0) {
if ((op->vt->r & VT_VALMASK) == VT_LLOCAL &&
op->is_memory) {
/* memory reference case (for both input and
output cases) */
SValue sv;
sv = *op->vt;
sv.r = (sv.r & ~VT_VALMASK) | VT_LOCAL;
load(op->reg, &sv);
} else if (i >= nb_outputs || op->is_rw) {
/* load value in register */
load(op->reg, op->vt);
if (op->is_llong) {
SValue sv;
sv = *op->vt;
sv.c.ul += 4;
load(TREG_EDX, &sv);
}
}
}
}
} else {
/* generate save code */
for(i = 0 ; i < nb_outputs; i++) {
op = &operands[i];
if (op->reg >= 0) {
if ((op->vt->r & VT_VALMASK) == VT_LLOCAL) {
if (!op->is_memory) {
SValue sv;
sv = *op->vt;
sv.r = (sv.r & ~VT_VALMASK) | VT_LOCAL;
load(out_reg, &sv);
sv.r = (sv.r & ~VT_VALMASK) | out_reg;
store(op->reg, &sv);
}
} else {
store(op->reg, op->vt);
if (op->is_llong) {
SValue sv;
sv = *op->vt;
sv.c.ul += 4;
store(TREG_EDX, &sv);
}
}
}
}
/* generate reg restore code */
for(i = NB_SAVED_REGS - 1; i >= 0; i--) {
reg = reg_saved[i];
if (regs_allocated[reg])
g(0x58 + reg);
}
}
}
static void asm_clobber(uint8_t *clobber_regs, const char *str)
{
int reg;
TokenSym *ts;
if (!strcmp(str, "memory") ||
!strcmp(str, "cc"))
return;
ts = tok_alloc(str, strlen(str));
reg = ts->tok;
if (reg >= TOK_ASM_eax && reg <= TOK_ASM_edi) {
reg -= TOK_ASM_eax;
} else if (reg >= TOK_ASM_ax && reg <= TOK_ASM_di) {
reg -= TOK_ASM_ax;
} else {
error("invalid clobber register '%s'", str);
}
clobber_regs[reg] = 1;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/i386-asm.c | C | lgpl | 36,588 |
#ifndef __GNU_STAB__
/* Indicate the GNU stab.h is in use. */
#define __GNU_STAB__
#define __define_stab(NAME, CODE, STRING) NAME=CODE,
enum __stab_debug_code
{
#include "stab.def"
LAST_UNUSED_STAB_CODE
};
#undef __define_stab
#endif /* __GNU_STAB_ */
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/stab.h | C | lgpl | 259 |
/*
* CIL code generator for TCC
*
* Copyright (c) 2002 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* number of available registers */
#define NB_REGS 3
/* a register can belong to several classes. The classes must be
sorted from more general to more precise (see gv2() code which does
assumptions on it). */
#define RC_ST 0x0001 /* any stack entry */
#define RC_ST0 0x0002 /* top of stack */
#define RC_ST1 0x0004 /* top - 1 */
#define RC_INT RC_ST
#define RC_FLOAT RC_ST
#define RC_IRET RC_ST0 /* function return: integer register */
#define RC_LRET RC_ST0 /* function return: second integer register */
#define RC_FRET RC_ST0 /* function return: float register */
/* pretty names for the registers */
enum {
REG_ST0 = 0,
REG_ST1,
REG_ST2,
};
int reg_classes[NB_REGS] = {
/* ST0 */ RC_ST | RC_ST0,
/* ST1 */ RC_ST | RC_ST1,
/* ST2 */ RC_ST,
};
/* return registers for function */
#define REG_IRET REG_ST0 /* single word int return register */
#define REG_LRET REG_ST0 /* second word return register (for long long) */
#define REG_FRET REG_ST0 /* float return register */
/* defined if function parameters must be evaluated in reverse order */
//#define INVERT_FUNC_PARAMS
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* pointer size, in bytes */
#define PTR_SIZE 4
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 8
#define LDOUBLE_ALIGN 8
/* function call context */
typedef struct GFuncContext {
int func_call; /* func call type (FUNC_STDCALL or FUNC_CDECL) */
} GFuncContext;
/******************************************************/
/* opcode definitions */
#define IL_OP_PREFIX 0xFE
enum ILOPCodes {
#define OP(name, str, n) IL_OP_ ## name = n,
#include "il-opcodes.h"
#undef OP
};
char *il_opcodes_str[] = {
#define OP(name, str, n) [n] = str,
#include "il-opcodes.h"
#undef OP
};
/******************************************************/
/* arguments variable numbers start from there */
#define ARG_BASE 0x70000000
static FILE *il_outfile;
static void out_byte(int c)
{
*(char *)ind++ = c;
}
static void out_le32(int c)
{
out_byte(c);
out_byte(c >> 8);
out_byte(c >> 16);
out_byte(c >> 24);
}
static void init_outfile(void)
{
if (!il_outfile) {
il_outfile = stdout;
fprintf(il_outfile,
".assembly extern mscorlib\n"
"{\n"
".ver 1:0:2411:0\n"
"}\n\n");
}
}
static void out_op1(int op)
{
if (op & 0x100)
out_byte(IL_OP_PREFIX);
out_byte(op & 0xff);
}
/* output an opcode with prefix */
static void out_op(int op)
{
out_op1(op);
fprintf(il_outfile, " %s\n", il_opcodes_str[op]);
}
static void out_opb(int op, int c)
{
out_op1(op);
out_byte(c);
fprintf(il_outfile, " %s %d\n", il_opcodes_str[op], c);
}
static void out_opi(int op, int c)
{
out_op1(op);
out_le32(c);
fprintf(il_outfile, " %s 0x%x\n", il_opcodes_str[op], c);
}
/* XXX: not complete */
static void il_type_to_str(char *buf, int buf_size,
int t, const char *varstr)
{
int bt;
Sym *s, *sa;
char buf1[256];
const char *tstr;
t = t & VT_TYPE;
bt = t & VT_BTYPE;
buf[0] = '\0';
if (t & VT_UNSIGNED)
pstrcat(buf, buf_size, "unsigned ");
switch(bt) {
case VT_VOID:
tstr = "void";
goto add_tstr;
case VT_BOOL:
tstr = "bool";
goto add_tstr;
case VT_BYTE:
tstr = "int8";
goto add_tstr;
case VT_SHORT:
tstr = "int16";
goto add_tstr;
case VT_ENUM:
case VT_INT:
case VT_LONG:
tstr = "int32";
goto add_tstr;
case VT_LLONG:
tstr = "int64";
goto add_tstr;
case VT_FLOAT:
tstr = "float32";
goto add_tstr;
case VT_DOUBLE:
case VT_LDOUBLE:
tstr = "float64";
add_tstr:
pstrcat(buf, buf_size, tstr);
break;
case VT_STRUCT:
error("structures not handled yet");
break;
case VT_FUNC:
s = sym_find((unsigned)t >> VT_STRUCT_SHIFT);
il_type_to_str(buf, buf_size, s->t, varstr);
pstrcat(buf, buf_size, "(");
sa = s->next;
while (sa != NULL) {
il_type_to_str(buf1, sizeof(buf1), sa->t, NULL);
pstrcat(buf, buf_size, buf1);
sa = sa->next;
if (sa)
pstrcat(buf, buf_size, ", ");
}
pstrcat(buf, buf_size, ")");
goto no_var;
case VT_PTR:
s = sym_find((unsigned)t >> VT_STRUCT_SHIFT);
pstrcpy(buf1, sizeof(buf1), "*");
if (varstr)
pstrcat(buf1, sizeof(buf1), varstr);
il_type_to_str(buf, buf_size, s->t, buf1);
goto no_var;
}
if (varstr) {
pstrcat(buf, buf_size, " ");
pstrcat(buf, buf_size, varstr);
}
no_var: ;
}
/* patch relocation entry with value 'val' */
void greloc_patch1(Reloc *p, int val)
{
}
/* output a symbol and patch all calls to it */
void gsym_addr(t, a)
{
}
/* output jump and return symbol */
static int out_opj(int op, int c)
{
out_op1(op);
out_le32(0);
if (c == 0) {
c = ind - (int)cur_text_section->data;
}
fprintf(il_outfile, " %s L%d\n", il_opcodes_str[op], c);
return c;
}
void gsym(int t)
{
fprintf(il_outfile, "L%d:\n", t);
}
/* load 'r' from value 'sv' */
void load(int r, SValue *sv)
{
int v, fc, ft;
v = sv->r & VT_VALMASK;
fc = sv->c.i;
ft = sv->t;
if (sv->r & VT_LVAL) {
if (v == VT_LOCAL) {
if (fc >= ARG_BASE) {
fc -= ARG_BASE;
if (fc >= 0 && fc <= 4) {
out_op(IL_OP_LDARG_0 + fc);
} else if (fc <= 0xff) {
out_opb(IL_OP_LDARG_S, fc);
} else {
out_opi(IL_OP_LDARG, fc);
}
} else {
if (fc >= 0 && fc <= 4) {
out_op(IL_OP_LDLOC_0 + fc);
} else if (fc <= 0xff) {
out_opb(IL_OP_LDLOC_S, fc);
} else {
out_opi(IL_OP_LDLOC, fc);
}
}
} else if (v == VT_CONST) {
/* XXX: handle globals */
out_opi(IL_OP_LDSFLD, 0);
} else {
if ((ft & VT_BTYPE) == VT_FLOAT) {
out_op(IL_OP_LDIND_R4);
} else if ((ft & VT_BTYPE) == VT_DOUBLE) {
out_op(IL_OP_LDIND_R8);
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
out_op(IL_OP_LDIND_R8);
} else if ((ft & VT_TYPE) == VT_BYTE)
out_op(IL_OP_LDIND_I1);
else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED))
out_op(IL_OP_LDIND_U1);
else if ((ft & VT_TYPE) == VT_SHORT)
out_op(IL_OP_LDIND_I2);
else if ((ft & VT_TYPE) == (VT_SHORT | VT_UNSIGNED))
out_op(IL_OP_LDIND_U2);
else
out_op(IL_OP_LDIND_I4);
}
} else {
if (v == VT_CONST) {
/* XXX: handle globals */
if (fc >= -1 && fc <= 8) {
out_op(IL_OP_LDC_I4_M1 + fc + 1);
} else {
out_opi(IL_OP_LDC_I4, fc);
}
} else if (v == VT_LOCAL) {
if (fc >= ARG_BASE) {
fc -= ARG_BASE;
if (fc <= 0xff) {
out_opb(IL_OP_LDARGA_S, fc);
} else {
out_opi(IL_OP_LDARGA, fc);
}
} else {
if (fc <= 0xff) {
out_opb(IL_OP_LDLOCA_S, fc);
} else {
out_opi(IL_OP_LDLOCA, fc);
}
}
} else {
/* XXX: do it */
}
}
}
/* store register 'r' in lvalue 'v' */
void store(int r, SValue *sv)
{
int v, fc, ft;
v = sv->r & VT_VALMASK;
fc = sv->c.i;
ft = sv->t;
if (v == VT_LOCAL) {
if (fc >= ARG_BASE) {
fc -= ARG_BASE;
/* XXX: check IL arg store semantics */
if (fc <= 0xff) {
out_opb(IL_OP_STARG_S, fc);
} else {
out_opi(IL_OP_STARG, fc);
}
} else {
if (fc >= 0 && fc <= 4) {
out_op(IL_OP_STLOC_0 + fc);
} else if (fc <= 0xff) {
out_opb(IL_OP_STLOC_S, fc);
} else {
out_opi(IL_OP_STLOC, fc);
}
}
} else if (v == VT_CONST) {
/* XXX: handle globals */
out_opi(IL_OP_STSFLD, 0);
} else {
if ((ft & VT_BTYPE) == VT_FLOAT)
out_op(IL_OP_STIND_R4);
else if ((ft & VT_BTYPE) == VT_DOUBLE)
out_op(IL_OP_STIND_R8);
else if ((ft & VT_BTYPE) == VT_LDOUBLE)
out_op(IL_OP_STIND_R8);
else if ((ft & VT_BTYPE) == VT_BYTE)
out_op(IL_OP_STIND_I1);
else if ((ft & VT_BTYPE) == VT_SHORT)
out_op(IL_OP_STIND_I2);
else
out_op(IL_OP_STIND_I4);
}
}
/* start function call and return function call context */
void gfunc_start(GFuncContext *c, int func_call)
{
c->func_call = func_call;
}
/* push function parameter which is in (vtop->t, vtop->c). Stack entry
is then popped. */
void gfunc_param(GFuncContext *c)
{
if ((vtop->t & VT_BTYPE) == VT_STRUCT) {
error("structures passed as value not handled yet");
} else {
/* simply push on stack */
gv(RC_ST0);
}
vtop--;
}
/* generate function call with address in (vtop->t, vtop->c) and free function
context. Stack entry is popped */
void gfunc_call(GFuncContext *c)
{
char buf[1024];
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* XXX: more info needed from tcc */
il_type_to_str(buf, sizeof(buf), vtop->t, "xxx");
fprintf(il_outfile, " call %s\n", buf);
} else {
/* indirect call */
gv(RC_INT);
il_type_to_str(buf, sizeof(buf), vtop->t, NULL);
fprintf(il_outfile, " calli %s\n", buf);
}
vtop--;
}
/* generate function prolog of type 't' */
void gfunc_prolog(int t)
{
int addr, u, func_call;
Sym *sym;
char buf[1024];
init_outfile();
/* XXX: pass function name to gfunc_prolog */
il_type_to_str(buf, sizeof(buf), t, funcname);
fprintf(il_outfile, ".method static %s il managed\n", buf);
fprintf(il_outfile, "{\n");
/* XXX: cannot do better now */
fprintf(il_outfile, " .maxstack %d\n", NB_REGS);
fprintf(il_outfile, " .locals (int32, int32, int32, int32, int32, int32, int32, int32)\n");
if (!strcmp(funcname, "main"))
fprintf(il_outfile, " .entrypoint\n");
sym = sym_find((unsigned)t >> VT_STRUCT_SHIFT);
func_call = sym->r;
addr = ARG_BASE;
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->t;
if ((func_vt & VT_BTYPE) == VT_STRUCT) {
func_vc = addr;
addr++;
}
/* define parameters */
while ((sym = sym->next) != NULL) {
u = sym->t;
sym_push(sym->v & ~SYM_FIELD, u,
VT_LOCAL | lvalue_type(sym->type.t), addr);
addr++;
}
}
/* generate function epilog */
void gfunc_epilog(void)
{
out_op(IL_OP_RET);
fprintf(il_outfile, "}\n\n");
}
/* generate a jump to a label */
int gjmp(int t)
{
return out_opj(IL_OP_BR, t);
}
/* generate a jump to a fixed address */
void gjmp_addr(int a)
{
/* XXX: handle syms */
out_opi(IL_OP_BR, a);
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
int gtst(int inv, int t)
{
int v, *p, c;
v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
c = vtop->c.i ^ inv;
switch(c) {
case TOK_EQ:
c = IL_OP_BEQ;
break;
case TOK_NE:
c = IL_OP_BNE_UN;
break;
case TOK_LT:
c = IL_OP_BLT;
break;
case TOK_LE:
c = IL_OP_BLE;
break;
case TOK_GT:
c = IL_OP_BGT;
break;
case TOK_GE:
c = IL_OP_BGE;
break;
case TOK_ULT:
c = IL_OP_BLT_UN;
break;
case TOK_ULE:
c = IL_OP_BLE_UN;
break;
case TOK_UGT:
c = IL_OP_BGT_UN;
break;
case TOK_UGE:
c = IL_OP_BGE_UN;
break;
}
t = out_opj(c, t);
} else if (v == VT_JMP || v == VT_JMPI) {
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
while (*p != 0)
p = (int *)*p;
*p = t;
t = vtop->c.i;
} else {
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->t)) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_FORWARD)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
v = gv(RC_INT);
t = out_opj(IL_OP_BRTRUE - inv, t);
}
}
vtop--;
return t;
}
/* generate an integer binary operation */
void gen_opi(int op)
{
gv2(RC_ST1, RC_ST0);
switch(op) {
case '+':
out_op(IL_OP_ADD);
goto std_op;
case '-':
out_op(IL_OP_SUB);
goto std_op;
case '&':
out_op(IL_OP_AND);
goto std_op;
case '^':
out_op(IL_OP_XOR);
goto std_op;
case '|':
out_op(IL_OP_OR);
goto std_op;
case '*':
out_op(IL_OP_MUL);
goto std_op;
case TOK_SHL:
out_op(IL_OP_SHL);
goto std_op;
case TOK_SHR:
out_op(IL_OP_SHR_UN);
goto std_op;
case TOK_SAR:
out_op(IL_OP_SHR);
goto std_op;
case '/':
case TOK_PDIV:
out_op(IL_OP_DIV);
goto std_op;
case TOK_UDIV:
out_op(IL_OP_DIV_UN);
goto std_op;
case '%':
out_op(IL_OP_REM);
goto std_op;
case TOK_UMOD:
out_op(IL_OP_REM_UN);
std_op:
vtop--;
vtop[0].r = REG_ST0;
break;
case TOK_EQ:
case TOK_NE:
case TOK_LT:
case TOK_LE:
case TOK_GT:
case TOK_GE:
case TOK_ULT:
case TOK_ULE:
case TOK_UGT:
case TOK_UGE:
vtop--;
vtop[0].r = VT_CMP;
vtop[0].c.i = op;
break;
}
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
void gen_opf(int op)
{
/* same as integer */
gen_opi(op);
}
/* convert integers to fp 't' type. Must handle 'int', 'unsigned int'
and 'long long' cases. */
void gen_cvt_itof(int t)
{
gv(RC_ST0);
if (t == VT_FLOAT)
out_op(IL_OP_CONV_R4);
else
out_op(IL_OP_CONV_R8);
}
/* convert fp to int 't' type */
/* XXX: handle long long case */
void gen_cvt_ftoi(int t)
{
gv(RC_ST0);
switch(t) {
case VT_INT | VT_UNSIGNED:
out_op(IL_OP_CONV_U4);
break;
case VT_LLONG:
out_op(IL_OP_CONV_I8);
break;
case VT_LLONG | VT_UNSIGNED:
out_op(IL_OP_CONV_U8);
break;
default:
out_op(IL_OP_CONV_I4);
break;
}
}
/* convert from one floating point type to another */
void gen_cvt_ftof(int t)
{
gv(RC_ST0);
if (t == VT_FLOAT) {
out_op(IL_OP_CONV_R4);
} else {
out_op(IL_OP_CONV_R8);
}
}
/* end of CIL code generator */
/*************************************************************/
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/il-gen.c | C | lgpl | 16,721 |
DEF_ASM_OP0(pusha, 0x60) /* must be first OP0 */
DEF_ASM_OP0(popa, 0x61)
DEF_ASM_OP0(clc, 0xf8)
DEF_ASM_OP0(cld, 0xfc)
DEF_ASM_OP0(cli, 0xfa)
DEF_ASM_OP0(clts, 0x0f06)
DEF_ASM_OP0(cmc, 0xf5)
DEF_ASM_OP0(lahf, 0x9f)
DEF_ASM_OP0(sahf, 0x9e)
DEF_ASM_OP0(pushfl, 0x9c)
DEF_ASM_OP0(popfl, 0x9d)
DEF_ASM_OP0(pushf, 0x9c)
DEF_ASM_OP0(popf, 0x9d)
DEF_ASM_OP0(stc, 0xf9)
DEF_ASM_OP0(std, 0xfd)
DEF_ASM_OP0(sti, 0xfb)
DEF_ASM_OP0(aaa, 0x37)
DEF_ASM_OP0(aas, 0x3f)
DEF_ASM_OP0(daa, 0x27)
DEF_ASM_OP0(das, 0x2f)
DEF_ASM_OP0(aad, 0xd50a)
DEF_ASM_OP0(aam, 0xd40a)
DEF_ASM_OP0(cbw, 0x6698)
DEF_ASM_OP0(cwd, 0x6699)
DEF_ASM_OP0(cwde, 0x98)
DEF_ASM_OP0(cdq, 0x99)
DEF_ASM_OP0(cbtw, 0x6698)
DEF_ASM_OP0(cwtl, 0x98)
DEF_ASM_OP0(cwtd, 0x6699)
DEF_ASM_OP0(cltd, 0x99)
DEF_ASM_OP0(int3, 0xcc)
DEF_ASM_OP0(into, 0xce)
DEF_ASM_OP0(iret, 0xcf)
DEF_ASM_OP0(rsm, 0x0faa)
DEF_ASM_OP0(hlt, 0xf4)
DEF_ASM_OP0(wait, 0x9b)
DEF_ASM_OP0(nop, 0x90)
DEF_ASM_OP0(xlat, 0xd7)
/* strings */
ALT(DEF_ASM_OP0L(cmpsb, 0xa6, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(scmpb, 0xa6, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(insb, 0x6c, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(outsb, 0x6e, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(lodsb, 0xac, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(slodb, 0xac, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(movsb, 0xa4, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(smovb, 0xa4, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(scasb, 0xae, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(sscab, 0xae, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(stosb, 0xaa, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(sstob, 0xaa, 0, OPC_BWL))
/* bits */
ALT(DEF_ASM_OP2(bsfw, 0x0fbc, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(bsrw, 0x0fbd, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(btw, 0x0fa3, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btw, 0x0fba, 4, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fab, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fba, 5, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fb3, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fba, 6, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fbb, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fba, 7, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
/* prefixes */
DEF_ASM_OP0(aword, 0x67)
DEF_ASM_OP0(addr16, 0x67)
DEF_ASM_OP0(word, 0x66)
DEF_ASM_OP0(data16, 0x66)
DEF_ASM_OP0(lock, 0xf0)
DEF_ASM_OP0(rep, 0xf3)
DEF_ASM_OP0(repe, 0xf3)
DEF_ASM_OP0(repz, 0xf3)
DEF_ASM_OP0(repne, 0xf2)
DEF_ASM_OP0(repnz, 0xf2)
DEF_ASM_OP0(invd, 0x0f08)
DEF_ASM_OP0(wbinvd, 0x0f09)
DEF_ASM_OP0(cpuid, 0x0fa2)
DEF_ASM_OP0(wrmsr, 0x0f30)
DEF_ASM_OP0(rdtsc, 0x0f31)
DEF_ASM_OP0(rdmsr, 0x0f32)
DEF_ASM_OP0(rdpmc, 0x0f33)
DEF_ASM_OP0(ud2, 0x0f0b)
/* NOTE: we took the same order as gas opcode definition order */
ALT(DEF_ASM_OP2(movb, 0xa0, 0, OPC_BWL, OPT_ADDR, OPT_EAX))
ALT(DEF_ASM_OP2(movb, 0xa2, 0, OPC_BWL, OPT_EAX, OPT_ADDR))
ALT(DEF_ASM_OP2(movb, 0x88, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movb, 0x8a, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xb0, 0, OPC_REG | OPC_BWL, OPT_IM, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xc6, 0, OPC_MODRM | OPC_BWL, OPT_IM, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(movw, 0x8c, 0, OPC_MODRM | OPC_WL, OPT_SEG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movw, 0x8e, 0, OPC_MODRM | OPC_WL, OPT_EA | OPT_REG, OPT_SEG))
ALT(DEF_ASM_OP2(movw, 0x0f20, 0, OPC_MODRM | OPC_WL, OPT_CR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f21, 0, OPC_MODRM | OPC_WL, OPT_DB, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f24, 0, OPC_MODRM | OPC_WL, OPT_TR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f22, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_CR))
ALT(DEF_ASM_OP2(movw, 0x0f23, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_DB))
ALT(DEF_ASM_OP2(movw, 0x0f26, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_TR))
ALT(DEF_ASM_OP2(movsbl, 0x0fbe, 0, OPC_MODRM, OPT_REG8 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(movsbw, 0x0fbe, 0, OPC_MODRM | OPC_D16, OPT_REG8 | OPT_EA, OPT_REG16))
ALT(DEF_ASM_OP2(movswl, 0x0fbf, 0, OPC_MODRM, OPT_REG16 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(movzbw, 0x0fb6, 0, OPC_MODRM | OPC_WL, OPT_REG8 | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(movzwl, 0x0fb7, 0, OPC_MODRM, OPT_REG16 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP1(pushw, 0x50, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(pushw, 0xff, 6, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(pushw, 0x6a, 0, OPC_WL, OPT_IM8S))
ALT(DEF_ASM_OP1(pushw, 0x68, 0, OPC_WL, OPT_IM32))
ALT(DEF_ASM_OP1(pushw, 0x06, 0, OPC_WL, OPT_SEG))
ALT(DEF_ASM_OP1(popw, 0x58, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(popw, 0x8f, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(popw, 0x07, 0, OPC_WL, OPT_SEG))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WL, OPT_REG, OPT_EAX))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WL, OPT_EAX, OPT_REG))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(inb, 0xe4, 0, OPC_BWL, OPT_IM8, OPT_EAX))
ALT(DEF_ASM_OP1(inb, 0xe4, 0, OPC_BWL, OPT_IM8))
ALT(DEF_ASM_OP2(inb, 0xec, 0, OPC_BWL, OPT_DX, OPT_EAX))
ALT(DEF_ASM_OP1(inb, 0xec, 0, OPC_BWL, OPT_DX))
ALT(DEF_ASM_OP2(outb, 0xe6, 0, OPC_BWL, OPT_EAX, OPT_IM8))
ALT(DEF_ASM_OP1(outb, 0xe6, 0, OPC_BWL, OPT_IM8))
ALT(DEF_ASM_OP2(outb, 0xee, 0, OPC_BWL, OPT_EAX, OPT_DX))
ALT(DEF_ASM_OP1(outb, 0xee, 0, OPC_BWL, OPT_DX))
ALT(DEF_ASM_OP2(leaw, 0x8d, 0, OPC_MODRM | OPC_WL, OPT_EA, OPT_REG))
ALT(DEF_ASM_OP2(les, 0xc4, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lds, 0xc5, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lss, 0x0fb2, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lfs, 0x0fb4, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lgs, 0x0fb5, 0, OPC_MODRM, OPT_EA, OPT_REG32))
/* arith */
ALT(DEF_ASM_OP2(addb, 0x00, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG)) /* XXX: use D bit ? */
ALT(DEF_ASM_OP2(addb, 0x02, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(addb, 0x04, 0, OPC_ARITH | OPC_BWL, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(addb, 0x80, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(addw, 0x83, 0, OPC_ARITH | OPC_MODRM | OPC_WL, OPT_IM8S, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0xa8, 0, OPC_BWL, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(testb, 0xf6, 0, OPC_MODRM | OPC_BWL, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP1(incw, 0x40, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(incb, 0xfe, 0, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(decw, 0x48, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(decb, 0xfe, 1, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(notb, 0xf6, 2, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(negb, 0xf6, 3, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(mulb, 0xf6, 4, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(imulb, 0xf6, 5, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(imulw, 0x0faf, 0, OPC_MODRM | OPC_WL, OPT_REG | OPT_EA, OPT_REG))
ALT(DEF_ASM_OP3(imulw, 0x6b, 0, OPC_MODRM | OPC_WL, OPT_IM8S, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x6b, 0, OPC_MODRM | OPC_WL, OPT_IM8S, OPT_REGW))
ALT(DEF_ASM_OP3(imulw, 0x69, 0, OPC_MODRM | OPC_WL, OPT_IMW, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x69, 0, OPC_MODRM | OPC_WL, OPT_IMW, OPT_REGW))
ALT(DEF_ASM_OP1(divb, 0xf6, 6, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(divb, 0xf6, 6, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA, OPT_EAX))
ALT(DEF_ASM_OP1(idivb, 0xf6, 7, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(idivb, 0xf6, 7, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA, OPT_EAX))
/* shifts */
ALT(DEF_ASM_OP2(rolb, 0xc0, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_IM8, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(rolb, 0xd2, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_CL, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP1(rolb, 0xd0, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP3(shldw, 0x0fa4, 0, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WL, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fac, 0, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WL, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP1(call, 0xff, 2, OPC_MODRM, OPT_INDIR))
ALT(DEF_ASM_OP1(call, 0xe8, 0, OPC_JMP, OPT_ADDR))
ALT(DEF_ASM_OP1(jmp, 0xff, 4, OPC_MODRM, OPT_INDIR))
ALT(DEF_ASM_OP1(jmp, 0xeb, 0, OPC_SHORTJMP | OPC_JMP, OPT_ADDR))
ALT(DEF_ASM_OP2(lcall, 0x9a, 0, 0, OPT_IM16, OPT_IM32))
ALT(DEF_ASM_OP1(lcall, 0xff, 3, 0, OPT_EA))
ALT(DEF_ASM_OP2(ljmp, 0xea, 0, 0, OPT_IM16, OPT_IM32))
ALT(DEF_ASM_OP1(ljmp, 0xff, 5, 0, OPT_EA))
ALT(DEF_ASM_OP1(int, 0xcd, 0, 0, OPT_IM8))
ALT(DEF_ASM_OP1(seto, 0x0f90, 0, OPC_MODRM | OPC_TEST, OPT_REG8 | OPT_EA))
DEF_ASM_OP2(enter, 0xc8, 0, 0, OPT_IM16, OPT_IM8)
DEF_ASM_OP0(leave, 0xc9)
DEF_ASM_OP0(ret, 0xc3)
ALT(DEF_ASM_OP1(ret, 0xc2, 0, 0, OPT_IM16))
DEF_ASM_OP0(lret, 0xcb)
ALT(DEF_ASM_OP1(lret, 0xca, 0, 0, OPT_IM16))
ALT(DEF_ASM_OP1(jo, 0x70, 0, OPC_SHORTJMP | OPC_JMP | OPC_TEST, OPT_ADDR))
DEF_ASM_OP1(loopne, 0xe0, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loopnz, 0xe0, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loope, 0xe1, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loopz, 0xe1, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loop, 0xe2, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(jecxz, 0xe3, 0, OPC_SHORTJMP, OPT_ADDR)
/* float */
/* specific fcomp handling */
ALT(DEF_ASM_OP0L(fcomp, 0xd8d9, 0, 0))
ALT(DEF_ASM_OP1(fadd, 0xd8c0, 0, OPC_FARITH | OPC_REG, OPT_ST))
ALT(DEF_ASM_OP2(fadd, 0xd8c0, 0, OPC_FARITH | OPC_REG, OPT_ST, OPT_ST0))
ALT(DEF_ASM_OP0L(fadd, 0xdec1, 0, OPC_FARITH))
ALT(DEF_ASM_OP1(faddp, 0xdec0, 0, OPC_FARITH | OPC_REG, OPT_ST))
ALT(DEF_ASM_OP2(faddp, 0xdec0, 0, OPC_FARITH | OPC_REG, OPT_ST, OPT_ST0))
ALT(DEF_ASM_OP2(faddp, 0xdec0, 0, OPC_FARITH | OPC_REG, OPT_ST0, OPT_ST))
ALT(DEF_ASM_OP0L(faddp, 0xdec1, 0, OPC_FARITH))
ALT(DEF_ASM_OP1(fadds, 0xd8, 0, OPC_FARITH | OPC_MODRM, OPT_EA))
ALT(DEF_ASM_OP1(fiaddl, 0xda, 0, OPC_FARITH | OPC_MODRM, OPT_EA))
ALT(DEF_ASM_OP1(faddl, 0xdc, 0, OPC_FARITH | OPC_MODRM, OPT_EA))
ALT(DEF_ASM_OP1(fiadds, 0xde, 0, OPC_FARITH | OPC_MODRM, OPT_EA))
DEF_ASM_OP0(fucompp, 0xdae9)
DEF_ASM_OP0(ftst, 0xd9e4)
DEF_ASM_OP0(fxam, 0xd9e5)
DEF_ASM_OP0(fld1, 0xd9e8)
DEF_ASM_OP0(fldl2t, 0xd9e9)
DEF_ASM_OP0(fldl2e, 0xd9ea)
DEF_ASM_OP0(fldpi, 0xd9eb)
DEF_ASM_OP0(fldlg2, 0xd9ec)
DEF_ASM_OP0(fldln2, 0xd9ed)
DEF_ASM_OP0(fldz, 0xd9ee)
DEF_ASM_OP0(f2xm1, 0xd9f0)
DEF_ASM_OP0(fyl2x, 0xd9f1)
DEF_ASM_OP0(fptan, 0xd9f2)
DEF_ASM_OP0(fpatan, 0xd9f3)
DEF_ASM_OP0(fxtract, 0xd9f4)
DEF_ASM_OP0(fprem1, 0xd9f5)
DEF_ASM_OP0(fdecstp, 0xd9f6)
DEF_ASM_OP0(fincstp, 0xd9f7)
DEF_ASM_OP0(fprem, 0xd9f8)
DEF_ASM_OP0(fyl2xp1, 0xd9f9)
DEF_ASM_OP0(fsqrt, 0xd9fa)
DEF_ASM_OP0(fsincos, 0xd9fb)
DEF_ASM_OP0(frndint, 0xd9fc)
DEF_ASM_OP0(fscale, 0xd9fd)
DEF_ASM_OP0(fsin, 0xd9fe)
DEF_ASM_OP0(fcos, 0xd9ff)
DEF_ASM_OP0(fchs, 0xd9e0)
DEF_ASM_OP0(fabs, 0xd9e1)
DEF_ASM_OP0(fninit, 0xdbe3)
DEF_ASM_OP0(fnclex, 0xdbe2)
DEF_ASM_OP0(fnop, 0xd9d0)
DEF_ASM_OP0(fwait, 0x9b)
/* fp load */
DEF_ASM_OP1(fld, 0xd9c0, 0, OPC_REG, OPT_ST)
DEF_ASM_OP1(fldl, 0xd9c0, 0, OPC_REG, OPT_ST)
DEF_ASM_OP1(flds, 0xd9, 0, OPC_MODRM, OPT_EA)
ALT(DEF_ASM_OP1(fldl, 0xdd, 0, OPC_MODRM, OPT_EA))
DEF_ASM_OP1(fildl, 0xdb, 0, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fildq, 0xdf, 5, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fildll, 0xdf, 5, OPC_MODRM,OPT_EA)
DEF_ASM_OP1(fldt, 0xdb, 5, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fbld, 0xdf, 4, OPC_MODRM, OPT_EA)
/* fp store */
DEF_ASM_OP1(fst, 0xddd0, 0, OPC_REG, OPT_ST)
DEF_ASM_OP1(fstl, 0xddd0, 0, OPC_REG, OPT_ST)
DEF_ASM_OP1(fsts, 0xd9, 2, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fstps, 0xd9, 3, OPC_MODRM, OPT_EA)
ALT(DEF_ASM_OP1(fstl, 0xdd, 2, OPC_MODRM, OPT_EA))
DEF_ASM_OP1(fstpl, 0xdd, 3, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fist, 0xdf, 2, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fistp, 0xdf, 3, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fistl, 0xdb, 2, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fistpl, 0xdb, 3, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fstp, 0xddd8, 0, OPC_REG, OPT_ST)
DEF_ASM_OP1(fistpq, 0xdf, 7, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fistpll, 0xdf, 7, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fstpt, 0xdb, 7, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(fbstp, 0xdf, 6, OPC_MODRM, OPT_EA)
/* exchange */
DEF_ASM_OP0(fxch, 0xd9c9)
ALT(DEF_ASM_OP1(fxch, 0xd9c8, 0, OPC_REG, OPT_ST))
/* misc FPU */
DEF_ASM_OP1(fucom, 0xdde0, 0, OPC_REG, OPT_ST )
DEF_ASM_OP1(fucomp, 0xdde8, 0, OPC_REG, OPT_ST )
DEF_ASM_OP0L(finit, 0xdbe3, 0, OPC_FWAIT)
DEF_ASM_OP1(fldcw, 0xd9, 5, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fnstcw, 0xd9, 7, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fstcw, 0xd9, 7, OPC_MODRM | OPC_FWAIT, OPT_EA )
DEF_ASM_OP0(fnstsw, 0xdfe0)
ALT(DEF_ASM_OP1(fnstsw, 0xdfe0, 0, 0, OPT_EAX ))
ALT(DEF_ASM_OP1(fnstsw, 0xdd, 7, OPC_MODRM, OPT_EA ))
DEF_ASM_OP1(fstsw, 0xdfe0, 0, OPC_FWAIT, OPT_EAX )
ALT(DEF_ASM_OP0L(fstsw, 0xdfe0, 0, OPC_FWAIT))
ALT(DEF_ASM_OP1(fstsw, 0xdd, 7, OPC_MODRM | OPC_FWAIT, OPT_EA ))
DEF_ASM_OP0L(fclex, 0xdbe2, 0, OPC_FWAIT)
DEF_ASM_OP1(fnstenv, 0xd9, 6, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fstenv, 0xd9, 6, OPC_MODRM | OPC_FWAIT, OPT_EA )
DEF_ASM_OP1(fldenv, 0xd9, 4, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fnsave, 0xdd, 6, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fsave, 0xdd, 6, OPC_MODRM | OPC_FWAIT, OPT_EA )
DEF_ASM_OP1(frstor, 0xdd, 4, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(ffree, 0xddc0, 4, OPC_REG, OPT_ST )
DEF_ASM_OP1(ffreep, 0xdfc0, 4, OPC_REG, OPT_ST )
DEF_ASM_OP1(fxsave, 0x0fae, 0, OPC_MODRM, OPT_EA )
DEF_ASM_OP1(fxrstor, 0x0fae, 1, OPC_MODRM, OPT_EA )
/* segments */
DEF_ASM_OP2(arpl, 0x63, 0, OPC_MODRM, OPT_REG16, OPT_REG16 | OPT_EA)
DEF_ASM_OP2(lar, 0x0f02, 0, OPC_MODRM, OPT_REG32 | OPT_EA, OPT_REG32)
DEF_ASM_OP1(lgdt, 0x0f01, 2, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(lidt, 0x0f01, 3, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(lldt, 0x0f00, 2, OPC_MODRM, OPT_EA | OPT_REG)
DEF_ASM_OP1(lmsw, 0x0f01, 6, OPC_MODRM, OPT_EA | OPT_REG)
ALT(DEF_ASM_OP2(lslw, 0x0f03, 0, OPC_MODRM | OPC_WL, OPT_EA | OPT_REG, OPT_REG))
DEF_ASM_OP1(ltr, 0x0f00, 3, OPC_MODRM, OPT_EA | OPT_REG)
DEF_ASM_OP1(sgdt, 0x0f01, 0, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(sidt, 0x0f01, 1, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(sldt, 0x0f00, 0, OPC_MODRM, OPT_REG | OPT_EA)
DEF_ASM_OP1(smsw, 0x0f01, 4, OPC_MODRM, OPT_REG | OPT_EA)
DEF_ASM_OP1(str, 0x0f00, 1, OPC_MODRM, OPT_REG16| OPT_EA)
DEF_ASM_OP1(verr, 0x0f00, 4, OPC_MODRM, OPT_REG | OPT_EA)
DEF_ASM_OP1(verw, 0x0f00, 5, OPC_MODRM, OPT_REG | OPT_EA)
/* 486 */
DEF_ASM_OP1(bswap, 0x0fc8, 0, OPC_REG, OPT_REG32 )
ALT(DEF_ASM_OP2(xaddb, 0x0fc0, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_REG | OPT_EA ))
ALT(DEF_ASM_OP2(cmpxchgb, 0x0fb0, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_REG | OPT_EA ))
DEF_ASM_OP1(invlpg, 0x0f01, 7, OPC_MODRM, OPT_EA )
DEF_ASM_OP2(boundl, 0x62, 0, OPC_MODRM, OPT_REG32, OPT_EA)
DEF_ASM_OP2(boundw, 0x62, 0, OPC_MODRM | OPC_D16, OPT_REG16, OPT_EA)
/* pentium */
DEF_ASM_OP1(cmpxchg8b, 0x0fc7, 1, OPC_MODRM, OPT_EA )
/* pentium pro */
ALT(DEF_ASM_OP2(cmovo, 0x0f40, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
DEF_ASM_OP2(fcmovb, 0xdac0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmove, 0xdac8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovbe, 0xdad0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovu, 0xdad8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovnb, 0xdbc0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovne, 0xdbc8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovnbe, 0xdbd0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovnu, 0xdbd8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fucomi, 0xdbe8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcomi, 0xdbf0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fucomip, 0xdfe8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcomip, 0xdff0, 0, OPC_REG, OPT_ST, OPT_ST0 )
/* mmx */
DEF_ASM_OP0(emms, 0x0f77) /* must be last OP0 */
DEF_ASM_OP2(movd, 0x0f6e, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_MMX )
ALT(DEF_ASM_OP2(movd, 0x0f7e, 0, OPC_MODRM, OPT_MMX, OPT_EA | OPT_REG32 ))
DEF_ASM_OP2(movq, 0x0f6f, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(movq, 0x0f7f, 0, OPC_MODRM, OPT_MMX, OPT_EA | OPT_MMX ))
DEF_ASM_OP2(packssdw, 0x0f6b, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(packsswb, 0x0f63, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(packuswb, 0x0f67, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddb, 0x0ffc, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddw, 0x0ffd, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddd, 0x0ffe, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddsb, 0x0fec, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddsw, 0x0fed, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddusb, 0x0fdc, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddusw, 0x0fdd, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pand, 0x0fdb, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pandn, 0x0fdf, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqb, 0x0f74, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqw, 0x0f75, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqd, 0x0f76, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtb, 0x0f64, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtw, 0x0f65, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtd, 0x0f66, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmaddwd, 0x0ff5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmulhw, 0x0fe5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmullw, 0x0fd5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(por, 0x0feb, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psllw, 0x0ff1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psllw, 0x0f71, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(pslld, 0x0ff2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(pslld, 0x0f72, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psllq, 0x0ff3, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psllq, 0x0f73, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psraw, 0x0fe1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psraw, 0x0f71, 4, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrad, 0x0fe2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrad, 0x0f72, 4, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrlw, 0x0fd1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrlw, 0x0f71, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrld, 0x0fd2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrld, 0x0f72, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrlq, 0x0fd3, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrlq, 0x0f73, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psubb, 0x0ff8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubw, 0x0ff9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubd, 0x0ffa, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubsb, 0x0fe8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubsw, 0x0fe9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubusb, 0x0fd8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubusw, 0x0fd9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhbw, 0x0f68, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhwd, 0x0f69, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhdq, 0x0f6a, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpcklbw, 0x0f60, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpcklwd, 0x0f61, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckldq, 0x0f62, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pxor, 0x0fef, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
#undef ALT
#undef DEF_ASM_OP0
#undef DEF_ASM_OP0L
#undef DEF_ASM_OP1
#undef DEF_ASM_OP2
#undef DEF_ASM_OP3
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/i386-asm.h | C | lgpl | 21,281 |
/*
* COFF file handling for TCC
*
* Copyright (c) 2003, 2004 TK
* Copyright (c) 2004 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "coff.h"
#define MAXNSCNS 255 /* MAXIMUM NUMBER OF SECTIONS */
#define MAX_STR_TABLE 1000000
AOUTHDR o_filehdr; /* OPTIONAL (A.OUT) FILE HEADER */
SCNHDR section_header[MAXNSCNS];
#define MAX_FUNCS 1000
#define MAX_FUNC_NAME_LENGTH 128
int nFuncs;
char Func[MAX_FUNCS][MAX_FUNC_NAME_LENGTH];
char AssociatedFile[MAX_FUNCS][MAX_FUNC_NAME_LENGTH];
int LineNoFilePtr[MAX_FUNCS];
int EndAddress[MAX_FUNCS];
int LastLineNo[MAX_FUNCS];
int FuncEntries[MAX_FUNCS];
BOOL OutputTheSection(Section * sect);
short int GetCoffFlags(const char *s);
void SortSymbolTable(void);
Section *FindSection(TCCState * s1, const char *sname);
int C67_main_entry_point;
int FindCoffSymbolIndex(const char *func_name);
int nb_syms;
typedef struct {
long tag;
long size;
long fileptr;
long nextsym;
short int dummy;
} AUXFUNC;
typedef struct {
long regmask;
unsigned short lineno;
unsigned short nentries;
int localframe;
int nextentry;
short int dummy;
} AUXBF;
typedef struct {
long dummy;
unsigned short lineno;
unsigned short dummy1;
int dummy2;
int dummy3;
unsigned short dummy4;
} AUXEF;
int tcc_output_coff(TCCState *s1, FILE *f)
{
Section *tcc_sect;
SCNHDR *coff_sec;
int file_pointer;
char *Coff_str_table, *pCoff_str_table;
int CoffTextSectionNo, coff_nb_syms;
FILHDR file_hdr; /* FILE HEADER STRUCTURE */
Section *stext, *sdata, *sbss;
int i, NSectionsToOutput = 0;
Coff_str_table = pCoff_str_table = NULL;
stext = FindSection(s1, ".text");
sdata = FindSection(s1, ".data");
sbss = FindSection(s1, ".bss");
nb_syms = symtab_section->data_offset / sizeof(Elf32_Sym);
coff_nb_syms = FindCoffSymbolIndex("XXXXXXXXXX1");
file_hdr.f_magic = COFF_C67_MAGIC; /* magic number */
file_hdr.f_timdat = 0; /* time & date stamp */
file_hdr.f_opthdr = sizeof(AOUTHDR); /* sizeof(optional hdr) */
file_hdr.f_flags = 0x1143; /* flags (copied from what code composer does) */
file_hdr.f_TargetID = 0x99; /* for C6x = 0x0099 */
o_filehdr.magic = 0x0108; /* see magic.h */
o_filehdr.vstamp = 0x0190; /* version stamp */
o_filehdr.tsize = stext->data_offset; /* text size in bytes, padded to FW bdry */
o_filehdr.dsize = sdata->data_offset; /* initialized data " " */
o_filehdr.bsize = sbss->data_offset; /* uninitialized data " " */
o_filehdr.entrypt = C67_main_entry_point; /* entry pt. */
o_filehdr.text_start = stext->sh_addr; /* base of text used for this file */
o_filehdr.data_start = sdata->sh_addr; /* base of data used for this file */
// create all the section headers
file_pointer = FILHSZ + sizeof(AOUTHDR);
CoffTextSectionNo = -1;
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
NSectionsToOutput++;
if (CoffTextSectionNo == -1 && tcc_sect == stext)
CoffTextSectionNo = NSectionsToOutput; // rem which coff sect number the .text sect is
strcpy(coff_sec->s_name, tcc_sect->name); /* section name */
coff_sec->s_paddr = tcc_sect->sh_addr; /* physical address */
coff_sec->s_vaddr = tcc_sect->sh_addr; /* virtual address */
coff_sec->s_size = tcc_sect->data_offset; /* section size */
coff_sec->s_scnptr = 0; /* file ptr to raw data for section */
coff_sec->s_relptr = 0; /* file ptr to relocation */
coff_sec->s_lnnoptr = 0; /* file ptr to line numbers */
coff_sec->s_nreloc = 0; /* number of relocation entries */
coff_sec->s_flags = GetCoffFlags(coff_sec->s_name); /* flags */
coff_sec->s_reserved = 0; /* reserved byte */
coff_sec->s_page = 0; /* memory page id */
file_pointer += sizeof(SCNHDR);
}
}
file_hdr.f_nscns = NSectionsToOutput; /* number of sections */
// now loop through and determine file pointer locations
// for the raw data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
// put raw data
coff_sec->s_scnptr = file_pointer; /* file ptr to raw data for section */
file_pointer += coff_sec->s_size;
}
}
// now loop through and determine file pointer locations
// for the relocation data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
// put relocations data
if (coff_sec->s_nreloc > 0) {
coff_sec->s_relptr = file_pointer; /* file ptr to relocation */
file_pointer += coff_sec->s_nreloc * sizeof(struct reloc);
}
}
}
// now loop through and determine file pointer locations
// for the line number data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
coff_sec->s_nlnno = 0;
coff_sec->s_lnnoptr = 0;
if (s1->do_debug && tcc_sect == stext) {
// count how many line nos data
// also find association between source file name and function
// so we can sort the symbol table
Stab_Sym *sym, *sym_end;
char func_name[MAX_FUNC_NAME_LENGTH],
last_func_name[MAX_FUNC_NAME_LENGTH];
unsigned long func_addr, last_pc, pc;
const char *incl_files[INCLUDE_STACK_SIZE];
int incl_index, len, last_line_num;
const char *str, *p;
coff_sec->s_lnnoptr = file_pointer; /* file ptr to linno */
func_name[0] = '\0';
func_addr = 0;
incl_index = 0;
last_func_name[0] = '\0';
last_pc = 0xffffffff;
last_line_num = 1;
sym = (Stab_Sym *) stab_section->data + 1;
sym_end =
(Stab_Sym *) (stab_section->data +
stab_section->data_offset);
nFuncs = 0;
while (sym < sym_end) {
switch (sym->n_type) {
/* function start or end */
case N_FUN:
if (sym->n_strx == 0) {
// end of function
coff_sec->s_nlnno++;
file_pointer += LINESZ;
pc = sym->n_value + func_addr;
func_name[0] = '\0';
func_addr = 0;
EndAddress[nFuncs] = pc;
FuncEntries[nFuncs] =
(file_pointer -
LineNoFilePtr[nFuncs]) / LINESZ - 1;
LastLineNo[nFuncs++] = last_line_num + 1;
} else {
// beginning of function
LineNoFilePtr[nFuncs] = file_pointer;
coff_sec->s_nlnno++;
file_pointer += LINESZ;
str =
(const char *) stabstr_section->data +
sym->n_strx;
p = strchr(str, ':');
if (!p) {
pstrcpy(func_name, sizeof(func_name), str);
pstrcpy(Func[nFuncs], sizeof(func_name), str);
} else {
len = p - str;
if (len > sizeof(func_name) - 1)
len = sizeof(func_name) - 1;
memcpy(func_name, str, len);
memcpy(Func[nFuncs], str, len);
func_name[len] = '\0';
}
// save the file that it came in so we can sort later
pstrcpy(AssociatedFile[nFuncs], sizeof(func_name),
incl_files[incl_index - 1]);
func_addr = sym->n_value;
}
break;
/* line number info */
case N_SLINE:
pc = sym->n_value + func_addr;
last_pc = pc;
last_line_num = sym->n_desc;
/* XXX: slow! */
strcpy(last_func_name, func_name);
coff_sec->s_nlnno++;
file_pointer += LINESZ;
break;
/* include files */
case N_BINCL:
str =
(const char *) stabstr_section->data + sym->n_strx;
add_incl:
if (incl_index < INCLUDE_STACK_SIZE) {
incl_files[incl_index++] = str;
}
break;
case N_EINCL:
if (incl_index > 1)
incl_index--;
break;
case N_SO:
if (sym->n_strx == 0) {
incl_index = 0; /* end of translation unit */
} else {
str =
(const char *) stabstr_section->data +
sym->n_strx;
/* do not add path */
len = strlen(str);
if (len > 0 && str[len - 1] != '/')
goto add_incl;
}
break;
}
sym++;
}
}
}
file_hdr.f_symptr = file_pointer; /* file pointer to symtab */
if (s1->do_debug)
file_hdr.f_nsyms = coff_nb_syms; /* number of symtab entries */
else
file_hdr.f_nsyms = 0;
file_pointer += file_hdr.f_nsyms * SYMNMLEN;
// OK now we are all set to write the file
fwrite(&file_hdr, FILHSZ, 1, f);
fwrite(&o_filehdr, sizeof(o_filehdr), 1, f);
// write section headers
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
fwrite(coff_sec, sizeof(SCNHDR), 1, f);
}
}
// write raw data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
fwrite(tcc_sect->data, tcc_sect->data_offset, 1, f);
}
}
// write relocation data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (OutputTheSection(tcc_sect)) {
// put relocations data
if (coff_sec->s_nreloc > 0) {
fwrite(tcc_sect->reloc,
coff_sec->s_nreloc * sizeof(struct reloc), 1, f);
}
}
}
// group the symbols in order of filename, func1, func2, etc
// finally global symbols
if (s1->do_debug)
SortSymbolTable();
// write line no data
for (i = 1; i < s1->nb_sections; i++) {
coff_sec = §ion_header[i];
tcc_sect = s1->sections[i];
if (s1->do_debug && tcc_sect == stext) {
// count how many line nos data
Stab_Sym *sym, *sym_end;
char func_name[128], last_func_name[128];
unsigned long func_addr, last_pc, pc;
const char *incl_files[INCLUDE_STACK_SIZE];
int incl_index, len, last_line_num;
const char *str, *p;
LINENO CoffLineNo;
func_name[0] = '\0';
func_addr = 0;
incl_index = 0;
last_func_name[0] = '\0';
last_pc = 0;
last_line_num = 1;
sym = (Stab_Sym *) stab_section->data + 1;
sym_end =
(Stab_Sym *) (stab_section->data +
stab_section->data_offset);
while (sym < sym_end) {
switch (sym->n_type) {
/* function start or end */
case N_FUN:
if (sym->n_strx == 0) {
// end of function
CoffLineNo.l_addr.l_paddr = last_pc;
CoffLineNo.l_lnno = last_line_num + 1;
fwrite(&CoffLineNo, 6, 1, f);
pc = sym->n_value + func_addr;
func_name[0] = '\0';
func_addr = 0;
} else {
// beginning of function
str =
(const char *) stabstr_section->data +
sym->n_strx;
p = strchr(str, ':');
if (!p) {
pstrcpy(func_name, sizeof(func_name), str);
} else {
len = p - str;
if (len > sizeof(func_name) - 1)
len = sizeof(func_name) - 1;
memcpy(func_name, str, len);
func_name[len] = '\0';
}
func_addr = sym->n_value;
last_pc = func_addr;
last_line_num = -1;
// output a function begin
CoffLineNo.l_addr.l_symndx =
FindCoffSymbolIndex(func_name);
CoffLineNo.l_lnno = 0;
fwrite(&CoffLineNo, 6, 1, f);
}
break;
/* line number info */
case N_SLINE:
pc = sym->n_value + func_addr;
/* XXX: slow! */
strcpy(last_func_name, func_name);
// output a line reference
CoffLineNo.l_addr.l_paddr = last_pc;
if (last_line_num == -1) {
CoffLineNo.l_lnno = sym->n_desc;
} else {
CoffLineNo.l_lnno = last_line_num + 1;
}
fwrite(&CoffLineNo, 6, 1, f);
last_pc = pc;
last_line_num = sym->n_desc;
break;
/* include files */
case N_BINCL:
str =
(const char *) stabstr_section->data + sym->n_strx;
add_incl2:
if (incl_index < INCLUDE_STACK_SIZE) {
incl_files[incl_index++] = str;
}
break;
case N_EINCL:
if (incl_index > 1)
incl_index--;
break;
case N_SO:
if (sym->n_strx == 0) {
incl_index = 0; /* end of translation unit */
} else {
str =
(const char *) stabstr_section->data +
sym->n_strx;
/* do not add path */
len = strlen(str);
if (len > 0 && str[len - 1] != '/')
goto add_incl2;
}
break;
}
sym++;
}
}
}
// write symbol table
if (s1->do_debug) {
int k;
struct syment csym;
AUXFUNC auxfunc;
AUXBF auxbf;
AUXEF auxef;
int i;
Elf32_Sym *p;
const char *name;
int nstr;
int n = 0;
Coff_str_table = (char *) tcc_malloc(MAX_STR_TABLE);
pCoff_str_table = Coff_str_table;
nstr = 0;
p = (Elf32_Sym *) symtab_section->data;
for (i = 0; i < nb_syms; i++) {
name = symtab_section->link->data + p->st_name;
for (k = 0; k < 8; k++)
csym._n._n_name[k] = 0;
if (strlen(name) <= 8) {
strcpy(csym._n._n_name, name);
} else {
if (pCoff_str_table - Coff_str_table + strlen(name) >
MAX_STR_TABLE - 1)
error("String table too large");
csym._n._n_n._n_zeroes = 0;
csym._n._n_n._n_offset =
pCoff_str_table - Coff_str_table + 4;
strcpy(pCoff_str_table, name);
pCoff_str_table += strlen(name) + 1; // skip over null
nstr++;
}
if (p->st_info == 4) {
// put a filename symbol
csym.n_value = 33; // ?????
csym.n_scnum = N_DEBUG;
csym.n_type = 0;
csym.n_sclass = C_FILE;
csym.n_numaux = 0;
fwrite(&csym, 18, 1, f);
n++;
} else if (p->st_info == 0x12) {
// find the function data
for (k = 0; k < nFuncs; k++) {
if (strcmp(name, Func[k]) == 0)
break;
}
if (k >= nFuncs) {
char s[256];
sprintf(s, "debug info can't find function: %s", name);
error(s);
}
// put a Function Name
csym.n_value = p->st_value; // physical address
csym.n_scnum = CoffTextSectionNo;
csym.n_type = MKTYPE(T_INT, DT_FCN, 0, 0, 0, 0, 0);
csym.n_sclass = C_EXT;
csym.n_numaux = 1;
fwrite(&csym, 18, 1, f);
// now put aux info
auxfunc.tag = 0;
auxfunc.size = EndAddress[k] - p->st_value;
auxfunc.fileptr = LineNoFilePtr[k];
auxfunc.nextsym = n + 6; // tktk
auxfunc.dummy = 0;
fwrite(&auxfunc, 18, 1, f);
// put a .bf
strcpy(csym._n._n_name, ".bf");
csym.n_value = p->st_value; // physical address
csym.n_scnum = CoffTextSectionNo;
csym.n_type = 0;
csym.n_sclass = C_FCN;
csym.n_numaux = 1;
fwrite(&csym, 18, 1, f);
// now put aux info
auxbf.regmask = 0;
auxbf.lineno = 0;
auxbf.nentries = FuncEntries[k];
auxbf.localframe = 0;
auxbf.nextentry = n + 6;
auxbf.dummy = 0;
fwrite(&auxbf, 18, 1, f);
// put a .ef
strcpy(csym._n._n_name, ".ef");
csym.n_value = EndAddress[k]; // physical address
csym.n_scnum = CoffTextSectionNo;
csym.n_type = 0;
csym.n_sclass = C_FCN;
csym.n_numaux = 1;
fwrite(&csym, 18, 1, f);
// now put aux info
auxef.dummy = 0;
auxef.lineno = LastLineNo[k];
auxef.dummy1 = 0;
auxef.dummy2 = 0;
auxef.dummy3 = 0;
auxef.dummy4 = 0;
fwrite(&auxef, 18, 1, f);
n += 6;
} else {
// try an put some type info
if ((p->st_other & VT_BTYPE) == VT_DOUBLE) {
csym.n_type = T_DOUBLE; // int
csym.n_sclass = C_EXT;
} else if ((p->st_other & VT_BTYPE) == VT_FLOAT) {
csym.n_type = T_FLOAT;
csym.n_sclass = C_EXT;
} else if ((p->st_other & VT_BTYPE) == VT_INT) {
csym.n_type = T_INT; // int
csym.n_sclass = C_EXT;
} else if ((p->st_other & VT_BTYPE) == VT_SHORT) {
csym.n_type = T_SHORT;
csym.n_sclass = C_EXT;
} else if ((p->st_other & VT_BTYPE) == VT_BYTE) {
csym.n_type = T_CHAR;
csym.n_sclass = C_EXT;
} else {
csym.n_type = T_INT; // just mark as a label
csym.n_sclass = C_LABEL;
}
csym.n_value = p->st_value;
csym.n_scnum = 2;
csym.n_numaux = 1;
fwrite(&csym, 18, 1, f);
auxfunc.tag = 0;
auxfunc.size = 0x20;
auxfunc.fileptr = 0;
auxfunc.nextsym = 0;
auxfunc.dummy = 0;
fwrite(&auxfunc, 18, 1, f);
n++;
n++;
}
p++;
}
}
if (s1->do_debug) {
// write string table
// first write the size
i = pCoff_str_table - Coff_str_table;
fwrite(&i, 4, 1, f);
// then write the strings
fwrite(Coff_str_table, i, 1, f);
tcc_free(Coff_str_table);
}
return 0;
}
// group the symbols in order of filename, func1, func2, etc
// finally global symbols
void SortSymbolTable(void)
{
int i, j, k, n = 0;
Elf32_Sym *p, *p2, *NewTable;
char *name, *name2;
NewTable = (Elf32_Sym *) tcc_malloc(nb_syms * sizeof(Elf32_Sym));
p = (Elf32_Sym *) symtab_section->data;
// find a file symbol, copy it over
// then scan the whole symbol list and copy any function
// symbols that match the file association
for (i = 0; i < nb_syms; i++) {
if (p->st_info == 4) {
name = (char *) symtab_section->link->data + p->st_name;
// this is a file symbol, copy it over
NewTable[n++] = *p;
p2 = (Elf32_Sym *) symtab_section->data;
for (j = 0; j < nb_syms; j++) {
if (p2->st_info == 0x12) {
// this is a func symbol
name2 =
(char *) symtab_section->link->data + p2->st_name;
// find the function data index
for (k = 0; k < nFuncs; k++) {
if (strcmp(name2, Func[k]) == 0)
break;
}
if (k >= nFuncs) {
char s[256];
sprintf(s,
"debug (sort) info can't find function: %s",
name2);
error(s);
}
if (strcmp(AssociatedFile[k], name) == 0) {
// yes they match copy it over
NewTable[n++] = *p2;
}
}
p2++;
}
}
p++;
}
// now all the filename and func symbols should have been copied over
// copy all the rest over (all except file and funcs)
p = (Elf32_Sym *) symtab_section->data;
for (i = 0; i < nb_syms; i++) {
if (p->st_info != 4 && p->st_info != 0x12) {
NewTable[n++] = *p;
}
p++;
}
if (n != nb_syms)
error("Internal Compiler error, debug info");
// copy it all back
p = (Elf32_Sym *) symtab_section->data;
for (i = 0; i < nb_syms; i++) {
*p++ = NewTable[i];
}
tcc_free(NewTable);
}
int FindCoffSymbolIndex(const char *func_name)
{
int i, n = 0;
Elf32_Sym *p;
char *name;
p = (Elf32_Sym *) symtab_section->data;
for (i = 0; i < nb_syms; i++) {
name = (char *) symtab_section->link->data + p->st_name;
if (p->st_info == 4) {
// put a filename symbol
n++;
} else if (p->st_info == 0x12) {
if (strcmp(func_name, name) == 0)
return n;
n += 6;
// put a Function Name
// now put aux info
// put a .bf
// now put aux info
// put a .ef
// now put aux info
} else {
n += 2;
}
p++;
}
return n; // total number of symbols
}
BOOL OutputTheSection(Section * sect)
{
const char *s = sect->name;
if (!strcmp(s, ".text"))
return true;
else if (!strcmp(s, ".data"))
return true;
else
return 0;
}
short int GetCoffFlags(const char *s)
{
if (!strcmp(s, ".text"))
return STYP_TEXT | STYP_DATA | STYP_ALIGN | 0x400;
else if (!strcmp(s, ".data"))
return STYP_DATA;
else if (!strcmp(s, ".bss"))
return STYP_BSS;
else if (!strcmp(s, ".stack"))
return STYP_BSS | STYP_ALIGN | 0x200;
else if (!strcmp(s, ".cinit"))
return STYP_COPY | STYP_DATA | STYP_ALIGN | 0x200;
else
return 0;
}
Section *FindSection(TCCState * s1, const char *sname)
{
Section *s;
int i;
for (i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (!strcmp(sname, s->name))
return s;
}
error("could not find section %s", sname);
return 0;
}
int tcc_load_coff(TCCState * s1, int fd)
{
// tktk TokenSym *ts;
FILE *f;
unsigned int str_size;
char *Coff_str_table, *name;
int i, k;
struct syment csym;
char name2[9];
FILHDR file_hdr; /* FILE HEADER STRUCTURE */
f = fdopen(fd, "rb");
if (!f) {
error("Unable to open .out file for input");
}
if (fread(&file_hdr, FILHSZ, 1, f) != 1)
error("error reading .out file for input");
if (fread(&o_filehdr, sizeof(o_filehdr), 1, f) != 1)
error("error reading .out file for input");
// first read the string table
if (fseek(f, file_hdr.f_symptr + file_hdr.f_nsyms * SYMESZ, SEEK_SET))
error("error reading .out file for input");
if (fread(&str_size, sizeof(int), 1, f) != 1)
error("error reading .out file for input");
Coff_str_table = (char *) tcc_malloc(str_size);
if (fread(Coff_str_table, str_size - 4, 1, f) != 1)
error("error reading .out file for input");
// read/process all the symbols
// seek back to symbols
if (fseek(f, file_hdr.f_symptr, SEEK_SET))
error("error reading .out file for input");
for (i = 0; i < file_hdr.f_nsyms; i++) {
if (fread(&csym, SYMESZ, 1, f) != 1)
error("error reading .out file for input");
if (csym._n._n_n._n_zeroes == 0) {
name = Coff_str_table + csym._n._n_n._n_offset - 4;
} else {
name = csym._n._n_name;
if (name[7] != 0) {
for (k = 0; k < 8; k++)
name2[k] = name[k];
name2[8] = 0;
name = name2;
}
}
// if (strcmp("_DAC_Buffer",name)==0) // tktk
// name[0]=0;
if (((csym.n_type & 0x30) == 0x20 && csym.n_sclass == 0x2) || ((csym.n_type & 0x30) == 0x30 && csym.n_sclass == 0x2) || (csym.n_type == 0x4 && csym.n_sclass == 0x2) || (csym.n_type == 0x8 && csym.n_sclass == 0x2) || // structures
(csym.n_type == 0x18 && csym.n_sclass == 0x2) || // pointer to structure
(csym.n_type == 0x7 && csym.n_sclass == 0x2) || // doubles
(csym.n_type == 0x6 && csym.n_sclass == 0x2)) // floats
{
// strip off any leading underscore (except for other main routine)
if (name[0] == '_' && strcmp(name, "_main") != 0)
name++;
tcc_add_symbol(s1, name, (void*)csym.n_value);
}
// skip any aux records
if (csym.n_numaux == 1) {
if (fread(&csym, SYMESZ, 1, f) != 1)
error("error reading .out file for input");
i++;
}
}
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/tcccoff.c | C | lgpl | 22,693 |
/*
* TMS320C67xx code generator for TCC
*
* Copyright (c) 2001, 2002 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//#define ASSEMBLY_LISTING_C67
/* number of available registers */
#define NB_REGS 24
/* a register can belong to several classes. The classes must be
sorted from more general to more precise (see gv2() code which does
assumptions on it). */
#define RC_INT 0x0001 /* generic integer register */
#define RC_FLOAT 0x0002 /* generic float register */
#define RC_EAX 0x0004
#define RC_ST0 0x0008
#define RC_ECX 0x0010
#define RC_EDX 0x0020
#define RC_INT_BSIDE 0x00000040 /* generic integer register on b side */
#define RC_C67_A4 0x00000100
#define RC_C67_A5 0x00000200
#define RC_C67_B4 0x00000400
#define RC_C67_B5 0x00000800
#define RC_C67_A6 0x00001000
#define RC_C67_A7 0x00002000
#define RC_C67_B6 0x00004000
#define RC_C67_B7 0x00008000
#define RC_C67_A8 0x00010000
#define RC_C67_A9 0x00020000
#define RC_C67_B8 0x00040000
#define RC_C67_B9 0x00080000
#define RC_C67_A10 0x00100000
#define RC_C67_A11 0x00200000
#define RC_C67_B10 0x00400000
#define RC_C67_B11 0x00800000
#define RC_C67_A12 0x01000000
#define RC_C67_A13 0x02000000
#define RC_C67_B12 0x04000000
#define RC_C67_B13 0x08000000
#define RC_IRET RC_C67_A4 /* function return: integer register */
#define RC_LRET RC_C67_A5 /* function return: second integer register */
#define RC_FRET RC_C67_A4 /* function return: float register */
/* pretty names for the registers */
enum {
TREG_EAX = 0, // really A2
TREG_ECX, // really A3
TREG_EDX, // really B0
TREG_ST0, // really B1
TREG_C67_A4,
TREG_C67_A5,
TREG_C67_B4,
TREG_C67_B5,
TREG_C67_A6,
TREG_C67_A7,
TREG_C67_B6,
TREG_C67_B7,
TREG_C67_A8,
TREG_C67_A9,
TREG_C67_B8,
TREG_C67_B9,
TREG_C67_A10,
TREG_C67_A11,
TREG_C67_B10,
TREG_C67_B11,
TREG_C67_A12,
TREG_C67_A13,
TREG_C67_B12,
TREG_C67_B13,
};
int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_FLOAT | RC_EAX,
// only allow even regs for floats (allow for doubles)
/* ecx */ RC_INT | RC_ECX,
/* edx */ RC_INT | RC_INT_BSIDE | RC_FLOAT | RC_EDX,
// only allow even regs for floats (allow for doubles)
/* st0 */ RC_INT | RC_INT_BSIDE | RC_ST0,
/* A4 */ RC_C67_A4,
/* A5 */ RC_C67_A5,
/* B4 */ RC_C67_B4,
/* B5 */ RC_C67_B5,
/* A6 */ RC_C67_A6,
/* A7 */ RC_C67_A7,
/* B6 */ RC_C67_B6,
/* B7 */ RC_C67_B7,
/* A8 */ RC_C67_A8,
/* A9 */ RC_C67_A9,
/* B8 */ RC_C67_B8,
/* B9 */ RC_C67_B9,
/* A10 */ RC_C67_A10,
/* A11 */ RC_C67_A11,
/* B10 */ RC_C67_B10,
/* B11 */ RC_C67_B11,
/* A12 */ RC_C67_A10,
/* A13 */ RC_C67_A11,
/* B12 */ RC_C67_B10,
/* B13 */ RC_C67_B11
};
/* return registers for function */
#define REG_IRET TREG_C67_A4 /* single word int return register */
#define REG_LRET TREG_C67_A5 /* second word return register (for long long) */
#define REG_FRET TREG_C67_A4 /* float return register */
#define ALWAYS_ASSERT(x) \
do {\
if (!(x))\
error("internal compiler error file at %s:%d", __FILE__, __LINE__);\
} while (0)
// although tcc thinks it is passing parameters on the stack,
// the C67 really passes up to the first 10 params in special
// regs or regs pairs (for 64 bit params). So keep track of
// the stack offsets so we can translate to the appropriate
// reg (pair)
#define NoCallArgsPassedOnStack 10
int NoOfCurFuncArgs;
int TranslateStackToReg[NoCallArgsPassedOnStack];
int ParamLocOnStack[NoCallArgsPassedOnStack];
int TotalBytesPushedOnStack;
/* defined if function parameters must be evaluated in reverse order */
//#define INVERT_FUNC_PARAMS
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* pointer size, in bytes */
#define PTR_SIZE 4
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 12
#define LDOUBLE_ALIGN 4
/* maximum alignment (for aligned attribute support) */
#define MAX_ALIGN 8
/******************************************************/
/* ELF defines */
#define EM_TCC_TARGET EM_C60
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_C60_32
#define R_JMP_SLOT R_C60_JMP_SLOT
#define R_COPY R_C60_COPY
#define ELF_START_ADDR 0x00000400
#define ELF_PAGE_SIZE 0x1000
/******************************************************/
static unsigned long func_sub_sp_offset;
static int func_ret_sub;
static BOOL C67_invert_test;
static int C67_compare_reg;
#ifdef ASSEMBLY_LISTING_C67
FILE *f = NULL;
#endif
void C67_g(int c)
{
int ind1;
#ifdef ASSEMBLY_LISTING_C67
fprintf(f, " %08X", c);
#endif
ind1 = ind + 4;
if (ind1 > (int) cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
cur_text_section->data[ind] = c & 0xff;
cur_text_section->data[ind + 1] = (c >> 8) & 0xff;
cur_text_section->data[ind + 2] = (c >> 16) & 0xff;
cur_text_section->data[ind + 3] = (c >> 24) & 0xff;
ind = ind1;
}
/* output a symbol and patch all calls to it */
void gsym_addr(int t, int a)
{
int n, *ptr;
while (t) {
ptr = (int *) (cur_text_section->data + t);
{
Sym *sym;
// extract 32 bit address from MVKH/MVKL
n = ((*ptr >> 7) & 0xffff);
n |= ((*(ptr + 1) >> 7) & 0xffff) << 16;
// define a label that will be relocated
sym = get_sym_ref(&char_pointer_type, cur_text_section, a, 0);
greloc(cur_text_section, sym, t, R_C60LO16);
greloc(cur_text_section, sym, t + 4, R_C60HI16);
// clear out where the pointer was
*ptr &= ~(0xffff << 7);
*(ptr + 1) &= ~(0xffff << 7);
}
t = n;
}
}
void gsym(int t)
{
gsym_addr(t, ind);
}
// these are regs that tcc doesn't really know about,
// but asign them unique values so the mapping routines
// can distinquish them
#define C67_A0 105
#define C67_SP 106
#define C67_B3 107
#define C67_FP 108
#define C67_B2 109
#define C67_CREG_ZERO -1 // Special code for no condition reg test
int ConvertRegToRegClass(int r)
{
// only works for A4-B13
return RC_C67_A4 << (r - TREG_C67_A4);
}
// map TCC reg to C67 reg number
int C67_map_regn(int r)
{
if (r == 0) // normal tcc regs
return 0x2; // A2
else if (r == 1) // normal tcc regs
return 3; // A3
else if (r == 2) // normal tcc regs
return 0; // B0
else if (r == 3) // normal tcc regs
return 1; // B1
else if (r >= TREG_C67_A4 && r <= TREG_C67_B13) // these form a pattern of alt pairs
return (((r & 0xfffffffc) >> 1) | (r & 1)) + 2;
else if (r == C67_A0)
return 0; // set to A0 (offset reg)
else if (r == C67_B2)
return 2; // set to B2 (offset reg)
else if (r == C67_B3)
return 3; // set to B3 (return address reg)
else if (r == C67_SP)
return 15; // set to SP (B15) (offset reg)
else if (r == C67_FP)
return 15; // set to FP (A15) (offset reg)
else if (r == C67_CREG_ZERO)
return 0; // Special code for no condition reg test
else
ALWAYS_ASSERT(FALSE);
return 0;
}
// mapping from tcc reg number to
// C67 register to condition code field
//
// valid condition code regs are:
//
// tcc reg 2 ->B0 -> 1
// tcc reg 3 ->B1 -> 2
// tcc reg 0 -> A2 -> 5
// tcc reg 1 -> A3 -> X
// tcc reg B2 -> 3
int C67_map_regc(int r)
{
if (r == 0) // normal tcc regs
return 0x5;
else if (r == 2) // normal tcc regs
return 0x1;
else if (r == 3) // normal tcc regs
return 0x2;
else if (r == C67_B2) // normal tcc regs
return 0x3;
else if (r == C67_CREG_ZERO)
return 0; // Special code for no condition reg test
else
ALWAYS_ASSERT(FALSE);
return 0;
}
// map TCC reg to C67 reg side A or B
int C67_map_regs(int r)
{
if (r == 0) // normal tcc regs
return 0x0;
else if (r == 1) // normal tcc regs
return 0x0;
else if (r == 2) // normal tcc regs
return 0x1;
else if (r == 3) // normal tcc regs
return 0x1;
else if (r >= TREG_C67_A4 && r <= TREG_C67_B13) // these form a pattern of alt pairs
return (r & 2) >> 1;
else if (r == C67_A0)
return 0; // set to A side
else if (r == C67_B2)
return 1; // set to B side
else if (r == C67_B3)
return 1; // set to B side
else if (r == C67_SP)
return 0x1; // set to SP (B15) B side
else if (r == C67_FP)
return 0x0; // set to FP (A15) A side
else
ALWAYS_ASSERT(FALSE);
return 0;
}
int C67_map_S12(char *s)
{
if (strstr(s, ".S1") != NULL)
return 0;
else if (strcmp(s, ".S2"))
return 1;
else
ALWAYS_ASSERT(FALSE);
return 0;
}
int C67_map_D12(char *s)
{
if (strstr(s, ".D1") != NULL)
return 0;
else if (strcmp(s, ".D2"))
return 1;
else
ALWAYS_ASSERT(FALSE);
return 0;
}
void C67_asm(char *s, int a, int b, int c)
{
BOOL xpath;
#ifdef ASSEMBLY_LISTING_C67
if (!f) {
f = fopen("TCC67_out.txt", "wt");
}
fprintf(f, "%04X ", ind);
#endif
if (strstr(s, "MVKL") == s) {
C67_g((C67_map_regn(b) << 23) |
((a & 0xffff) << 7) | (0x0a << 2) | (C67_map_regs(b) << 1));
} else if (strstr(s, "MVKH") == s) {
C67_g((C67_map_regn(b) << 23) |
(((a >> 16) & 0xffff) << 7) |
(0x1a << 2) | (C67_map_regs(b) << 1));
} else if (strstr(s, "STW.D SP POST DEC") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //SP B15
(2 << 13) | //ucst5 (must keep 8 byte boundary !!)
(0xa << 9) | //mode a = post dec ucst
(0 << 8) | //r (LDDW bit 0)
(1 << 7) | //y D1/D2 use B side
(7 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STB.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(3 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STH.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(5 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STB.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(3 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STH.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(5 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STW.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(7 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STW.D *") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(C67_map_regn(b) << 18) | //base reg A0
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(b) << 7) | //y D1/D2 base reg side
(7 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STH.D *") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(C67_map_regn(b) << 18) | //base reg A0
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(b) << 7) | //y D1/D2 base reg side
(5 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STB.D *") == s) {
C67_g((C67_map_regn(a) << 23) | //src
(C67_map_regn(b) << 18) | //base reg A0
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(b) << 7) | //y D1/D2 base reg side
(3 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "STW.D +*") == s) {
ALWAYS_ASSERT(c < 32);
C67_g((C67_map_regn(a) << 23) | //src
(C67_map_regn(b) << 18) | //base reg A0
(c << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(b) << 7) | //y D1/D2 base reg side
(7 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of src
(0 << 0)); //parallel
} else if (strstr(s, "LDW.D SP PRE INC") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg B15
(2 << 13) | //ucst5 (must keep 8 byte boundary)
(9 << 9) | //mode 9 = pre inc ucst5
(0 << 8) | //r (LDDW bit 0)
(1 << 7) | //y D1/D2 B side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDDW.D SP PRE INC") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg B15
(1 << 13) | //ucst5 (must keep 8 byte boundary)
(9 << 9) | //mode 9 = pre inc ucst5
(1 << 8) | //r (LDDW bit 1)
(1 << 7) | //y D1/D2 B side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDW.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDDW.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(1 << 8) | //r (LDDW bit 1)
(0 << 7) | //y D1/D2 A side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDH.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(4 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDB.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(2 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDHU.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(0 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDBU.D *+SP[A0]") == s) {
C67_g((C67_map_regn(a) << 23) | //dst
(15 << 18) | //base reg A15
(0 << 13) | //offset reg A0
(5 << 9) | //mode 5 = pos offset, base reg + off reg
(0 << 8) | //r (LDDW bit 0)
(0 << 7) | //y D1/D2 A side
(1 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(a) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDW.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDDW.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(1 << 8) | //r (LDDW bit 1)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDH.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(4 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDB.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(2 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDHU.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(0 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDBU.D *") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(0 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(1 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "LDW.D +*") == s) {
C67_g((C67_map_regn(b) << 23) | //dst
(C67_map_regn(a) << 18) | //base reg A15
(1 << 13) | //cst5
(1 << 9) | //mode 1 = pos cst offset
(0 << 8) | //r (LDDW bit 0)
(C67_map_regs(a) << 7) | //y D1/D2 src side
(6 << 4) | //ldst 3=STB, 5=STH 5, 7=STW, 6=LDW 4=LDH 2=LDB 0=LDHU 1=LDBU
(1 << 2) | //opcode
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "CMPLTSP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x3a << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPGTSP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x39 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPEQSP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x38 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
}
else if (strstr(s, "CMPLTDP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x2a << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPGTDP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x29 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPEQDP") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x28 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPLT") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x57 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPGT") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x47 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPEQ") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x53 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPLTU") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x5f << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "CMPGTU") == s) {
xpath = C67_map_regs(a) ^ C67_map_regs(b);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x use cross path for src2
(0x4f << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side for reg c
(0 << 0)); //parallel
} else if (strstr(s, "B DISP") == s) {
C67_g((0 << 29) | //creg
(0 << 28) | //z
(a << 7) | //cnst
(0x4 << 2) | //opcode fixed
(0 << 1) | //S0/S1
(0 << 0)); //parallel
} else if (strstr(s, "B.") == s) {
xpath = C67_map_regs(c) ^ 1;
C67_g((C67_map_regc(b) << 29) | //creg
(a << 28) | //inv
(0 << 23) | //dst
(C67_map_regn(c) << 18) | //src2
(0 << 13) | //
(xpath << 12) | //x cross path if !B side
(0xd << 6) | //opcode
(0x8 << 2) | //opcode fixed
(1 << 1) | //must be S2
(0 << 0)); //parallel
} else if (strstr(s, "MV.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 (cst5)
(xpath << 12) | //x cross path if opposite sides
(0x2 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SPTRUNC.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0xb << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "DPTRUNC.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
((C67_map_regn(b) + 1) << 18) | //src2 WEIRD CPU must specify odd reg for some reason
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x1 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "INTSP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x4a << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "INTSPU.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x49 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "INTDP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x39 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "INTDPU.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
((C67_map_regn(b) + 1) << 18) | //src2 WEIRD CPU must specify odd reg for some reason
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x3b << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SPDP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(0 << 13) | //src1 NA
(xpath << 12) | //x cross path if opposite sides
(0x2 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "DPSP.L") == s) {
ALWAYS_ASSERT(C67_map_regs(b) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
((C67_map_regn(b) + 1) << 18) | //src2 WEIRD CPU must specify odd reg for some reason
(0 << 13) | //src1 NA
(0 << 12) | //x cross path if opposite sides
(0x9 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "ADD.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x3 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SUB.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x7 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "OR.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x7f << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "AND.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x7b << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "XOR.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x6f << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "ADDSP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x10 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "ADDDP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x18 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SUBSP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x11 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SUBDP.L") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x19 << 5) | //opcode
(0x6 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "MPYSP.M") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x1c << 7) | //opcode
(0x0 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "MPYDP.M") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2 (possible x path)
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x0e << 7) | //opcode
(0x0 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "MPYI.M") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(a) == C67_map_regs(c));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1 (cst5)
(xpath << 12) | //x cross path if opposite sides
(0x4 << 7) | //opcode
(0x0 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SHR.S") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x37 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SHRU.S") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x27 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "SHL.S") == s) {
xpath = C67_map_regs(b) ^ C67_map_regs(c);
ALWAYS_ASSERT(C67_map_regs(c) == C67_map_regs(a));
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(c) << 23) | //dst
(C67_map_regn(b) << 18) | //src2
(C67_map_regn(a) << 13) | //src1
(xpath << 12) | //x cross path if opposite sides
(0x33 << 6) | //opcode
(0x8 << 2) | //opcode fixed
(C67_map_regs(c) << 1) | //side of dest
(0 << 0)); //parallel
} else if (strstr(s, "||ADDK") == s) {
xpath = 0; // no xpath required just use the side of the src/dst
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(b) << 23) | //dst
(a << 07) | //scst16
(0x14 << 2) | //opcode fixed
(C67_map_regs(b) << 1) | //side of dst
(1 << 0)); //parallel
} else if (strstr(s, "ADDK") == s) {
xpath = 0; // no xpath required just use the side of the src/dst
C67_g((0 << 29) | //creg
(0 << 28) | //inv
(C67_map_regn(b) << 23) | //dst
(a << 07) | //scst16
(0x14 << 2) | //opcode fixed
(C67_map_regs(b) << 1) | //side of dst
(0 << 0)); //parallel
} else if (strstr(s, "NOP") == s) {
C67_g(((a - 1) << 13) | //no of cycles
(0 << 0)); //parallel
} else
ALWAYS_ASSERT(FALSE);
#ifdef ASSEMBLY_LISTING_C67
fprintf(f, " %s %d %d %d\n", s, a, b, c);
#endif
}
//r=reg to load, fr=from reg, symbol for relocation, constant
void C67_MVKL(int r, int fc)
{
C67_asm("MVKL.", fc, r, 0);
}
void C67_MVKH(int r, int fc)
{
C67_asm("MVKH.", fc, r, 0);
}
void C67_STB_SP_A0(int r)
{
C67_asm("STB.D *+SP[A0]", r, 0, 0); // STB r,*+SP[A0]
}
void C67_STH_SP_A0(int r)
{
C67_asm("STH.D *+SP[A0]", r, 0, 0); // STH r,*+SP[A0]
}
void C67_STW_SP_A0(int r)
{
C67_asm("STW.D *+SP[A0]", r, 0, 0); // STW r,*+SP[A0]
}
void C67_STB_PTR(int r, int r2)
{
C67_asm("STB.D *", r, r2, 0); // STB r, *r2
}
void C67_STH_PTR(int r, int r2)
{
C67_asm("STH.D *", r, r2, 0); // STH r, *r2
}
void C67_STW_PTR(int r, int r2)
{
C67_asm("STW.D *", r, r2, 0); // STW r, *r2
}
void C67_STW_PTR_PRE_INC(int r, int r2, int n)
{
C67_asm("STW.D +*", r, r2, n); // STW r, *+r2
}
void C67_PUSH(int r)
{
C67_asm("STW.D SP POST DEC", r, 0, 0); // STW r,*SP--
}
void C67_LDW_SP_A0(int r)
{
C67_asm("LDW.D *+SP[A0]", r, 0, 0); // LDW *+SP[A0],r
}
void C67_LDDW_SP_A0(int r)
{
C67_asm("LDDW.D *+SP[A0]", r, 0, 0); // LDDW *+SP[A0],r
}
void C67_LDH_SP_A0(int r)
{
C67_asm("LDH.D *+SP[A0]", r, 0, 0); // LDH *+SP[A0],r
}
void C67_LDB_SP_A0(int r)
{
C67_asm("LDB.D *+SP[A0]", r, 0, 0); // LDB *+SP[A0],r
}
void C67_LDHU_SP_A0(int r)
{
C67_asm("LDHU.D *+SP[A0]", r, 0, 0); // LDHU *+SP[A0],r
}
void C67_LDBU_SP_A0(int r)
{
C67_asm("LDBU.D *+SP[A0]", r, 0, 0); // LDBU *+SP[A0],r
}
void C67_LDW_PTR(int r, int r2)
{
C67_asm("LDW.D *", r, r2, 0); // LDW *r,r2
}
void C67_LDDW_PTR(int r, int r2)
{
C67_asm("LDDW.D *", r, r2, 0); // LDDW *r,r2
}
void C67_LDH_PTR(int r, int r2)
{
C67_asm("LDH.D *", r, r2, 0); // LDH *r,r2
}
void C67_LDB_PTR(int r, int r2)
{
C67_asm("LDB.D *", r, r2, 0); // LDB *r,r2
}
void C67_LDHU_PTR(int r, int r2)
{
C67_asm("LDHU.D *", r, r2, 0); // LDHU *r,r2
}
void C67_LDBU_PTR(int r, int r2)
{
C67_asm("LDBU.D *", r, r2, 0); // LDBU *r,r2
}
void C67_LDW_PTR_PRE_INC(int r, int r2)
{
C67_asm("LDW.D +*", r, r2, 0); // LDW *+r,r2
}
void C67_POP(int r)
{
C67_asm("LDW.D SP PRE INC", r, 0, 0); // LDW *++SP,r
}
void C67_POP_DW(int r)
{
C67_asm("LDDW.D SP PRE INC", r, 0, 0); // LDDW *++SP,r
}
void C67_CMPLT(int s1, int s2, int dst)
{
C67_asm("CMPLT.L1", s1, s2, dst);
}
void C67_CMPGT(int s1, int s2, int dst)
{
C67_asm("CMPGT.L1", s1, s2, dst);
}
void C67_CMPEQ(int s1, int s2, int dst)
{
C67_asm("CMPEQ.L1", s1, s2, dst);
}
void C67_CMPLTU(int s1, int s2, int dst)
{
C67_asm("CMPLTU.L1", s1, s2, dst);
}
void C67_CMPGTU(int s1, int s2, int dst)
{
C67_asm("CMPGTU.L1", s1, s2, dst);
}
void C67_CMPLTSP(int s1, int s2, int dst)
{
C67_asm("CMPLTSP.S1", s1, s2, dst);
}
void C67_CMPGTSP(int s1, int s2, int dst)
{
C67_asm("CMPGTSP.S1", s1, s2, dst);
}
void C67_CMPEQSP(int s1, int s2, int dst)
{
C67_asm("CMPEQSP.S1", s1, s2, dst);
}
void C67_CMPLTDP(int s1, int s2, int dst)
{
C67_asm("CMPLTDP.S1", s1, s2, dst);
}
void C67_CMPGTDP(int s1, int s2, int dst)
{
C67_asm("CMPGTDP.S1", s1, s2, dst);
}
void C67_CMPEQDP(int s1, int s2, int dst)
{
C67_asm("CMPEQDP.S1", s1, s2, dst);
}
void C67_IREG_B_REG(int inv, int r1, int r2) // [!R] B r2
{
C67_asm("B.S2", inv, r1, r2);
}
// call with how many 32 bit words to skip
// (0 would branch to the branch instruction)
void C67_B_DISP(int disp) // B +2 Branch with constant displacement
{
// Branch point is relative to the 8 word fetch packet
//
// we will assume the text section always starts on an 8 word (32 byte boundary)
//
// so add in how many words into the fetch packet the branch is
C67_asm("B DISP", disp + ((ind & 31) >> 2), 0, 0);
}
void C67_NOP(int n)
{
C67_asm("NOP", n, 0, 0);
}
void C67_ADDK(int n, int r)
{
ALWAYS_ASSERT(abs(n) < 32767);
C67_asm("ADDK", n, r, 0);
}
void C67_ADDK_PARALLEL(int n, int r)
{
ALWAYS_ASSERT(abs(n) < 32767);
C67_asm("||ADDK", n, r, 0);
}
void C67_Adjust_ADDK(int *inst, int n)
{
ALWAYS_ASSERT(abs(n) < 32767);
*inst = (*inst & (~(0xffff << 7))) | ((n & 0xffff) << 7);
}
void C67_MV(int r, int v)
{
C67_asm("MV.L", 0, r, v);
}
void C67_DPTRUNC(int r, int v)
{
C67_asm("DPTRUNC.L", 0, r, v);
}
void C67_SPTRUNC(int r, int v)
{
C67_asm("SPTRUNC.L", 0, r, v);
}
void C67_INTSP(int r, int v)
{
C67_asm("INTSP.L", 0, r, v);
}
void C67_INTDP(int r, int v)
{
C67_asm("INTDP.L", 0, r, v);
}
void C67_INTSPU(int r, int v)
{
C67_asm("INTSPU.L", 0, r, v);
}
void C67_INTDPU(int r, int v)
{
C67_asm("INTDPU.L", 0, r, v);
}
void C67_SPDP(int r, int v)
{
C67_asm("SPDP.L", 0, r, v);
}
void C67_DPSP(int r, int v) // note regs must be on the same side
{
C67_asm("DPSP.L", 0, r, v);
}
void C67_ADD(int r, int v)
{
C67_asm("ADD.L", v, r, v);
}
void C67_SUB(int r, int v)
{
C67_asm("SUB.L", v, r, v);
}
void C67_AND(int r, int v)
{
C67_asm("AND.L", v, r, v);
}
void C67_OR(int r, int v)
{
C67_asm("OR.L", v, r, v);
}
void C67_XOR(int r, int v)
{
C67_asm("XOR.L", v, r, v);
}
void C67_ADDSP(int r, int v)
{
C67_asm("ADDSP.L", v, r, v);
}
void C67_SUBSP(int r, int v)
{
C67_asm("SUBSP.L", v, r, v);
}
void C67_MPYSP(int r, int v)
{
C67_asm("MPYSP.M", v, r, v);
}
void C67_ADDDP(int r, int v)
{
C67_asm("ADDDP.L", v, r, v);
}
void C67_SUBDP(int r, int v)
{
C67_asm("SUBDP.L", v, r, v);
}
void C67_MPYDP(int r, int v)
{
C67_asm("MPYDP.M", v, r, v);
}
void C67_MPYI(int r, int v)
{
C67_asm("MPYI.M", v, r, v);
}
void C67_SHL(int r, int v)
{
C67_asm("SHL.S", r, v, v);
}
void C67_SHRU(int r, int v)
{
C67_asm("SHRU.S", r, v, v);
}
void C67_SHR(int r, int v)
{
C67_asm("SHR.S", r, v, v);
}
/* load 'r' from value 'sv' */
void load(int r, SValue * sv)
{
int v, t, ft, fc, fr, size = 0, element;
BOOL Unsigned = false;
SValue v1;
fr = sv->r;
ft = sv->type.t;
fc = sv->c.ul;
v = fr & VT_VALMASK;
if (fr & VT_LVAL) {
if (v == VT_LLOCAL) {
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fr = r;
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
error("long double not supported");
} else if ((ft & VT_TYPE) == VT_BYTE) {
size = 1;
} else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED)) {
size = 1;
Unsigned = TRUE;
} else if ((ft & VT_TYPE) == VT_SHORT) {
size = 2;
} else if ((ft & VT_TYPE) == (VT_SHORT | VT_UNSIGNED)) {
size = 2;
Unsigned = TRUE;
} else if ((ft & VT_BTYPE) == VT_DOUBLE) {
size = 8;
} else {
size = 4;
}
// check if fc is a positive reference on the stack,
// if it is tcc is referencing what it thinks is a parameter
// on the stack, so check if it is really in a register.
if (v == VT_LOCAL && fc > 0) {
int stack_pos = 8;
for (t = 0; t < NoCallArgsPassedOnStack; t++) {
if (fc == stack_pos)
break;
stack_pos += TranslateStackToReg[t];
}
// param has been pushed on stack, get it like a local var
fc = ParamLocOnStack[t] - 8;
}
if ((fr & VT_VALMASK) < VT_CONST) // check for pure indirect
{
if (size == 1) {
if (Unsigned)
C67_LDBU_PTR(v, r); // LDBU *v,r
else
C67_LDB_PTR(v, r); // LDB *v,r
} else if (size == 2) {
if (Unsigned)
C67_LDHU_PTR(v, r); // LDHU *v,r
else
C67_LDH_PTR(v, r); // LDH *v,r
} else if (size == 4) {
C67_LDW_PTR(v, r); // LDW *v,r
} else if (size == 8) {
C67_LDDW_PTR(v, r); // LDDW *v,r
}
C67_NOP(4); // NOP 4
return;
} else if (fr & VT_SYM) {
greloc(cur_text_section, sv->sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, sv->sym, ind + 4, R_C60HI16);
C67_MVKL(C67_A0, fc); //r=reg to load, constant
C67_MVKH(C67_A0, fc); //r=reg to load, constant
if (size == 1) {
if (Unsigned)
C67_LDBU_PTR(C67_A0, r); // LDBU *A0,r
else
C67_LDB_PTR(C67_A0, r); // LDB *A0,r
} else if (size == 2) {
if (Unsigned)
C67_LDHU_PTR(C67_A0, r); // LDHU *A0,r
else
C67_LDH_PTR(C67_A0, r); // LDH *A0,r
} else if (size == 4) {
C67_LDW_PTR(C67_A0, r); // LDW *A0,r
} else if (size == 8) {
C67_LDDW_PTR(C67_A0, r); // LDDW *A0,r
}
C67_NOP(4); // NOP 4
return;
} else {
element = size;
// divide offset in bytes to create element index
C67_MVKL(C67_A0, (fc / element) + 8 / element); //r=reg to load, constant
C67_MVKH(C67_A0, (fc / element) + 8 / element); //r=reg to load, constant
if (size == 1) {
if (Unsigned)
C67_LDBU_SP_A0(r); // LDBU r, SP[A0]
else
C67_LDB_SP_A0(r); // LDB r, SP[A0]
} else if (size == 2) {
if (Unsigned)
C67_LDHU_SP_A0(r); // LDHU r, SP[A0]
else
C67_LDH_SP_A0(r); // LDH r, SP[A0]
} else if (size == 4) {
C67_LDW_SP_A0(r); // LDW r, SP[A0]
} else if (size == 8) {
C67_LDDW_SP_A0(r); // LDDW r, SP[A0]
}
C67_NOP(4); // NOP 4
return;
}
} else {
if (v == VT_CONST) {
if (fr & VT_SYM) {
greloc(cur_text_section, sv->sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, sv->sym, ind + 4, R_C60HI16);
}
C67_MVKL(r, fc); //r=reg to load, constant
C67_MVKH(r, fc); //r=reg to load, constant
} else if (v == VT_LOCAL) {
C67_MVKL(r, fc + 8); //r=reg to load, constant C67 stack points to next free
C67_MVKH(r, fc + 8); //r=reg to load, constant
C67_ADD(C67_FP, r); // MV v,r v -> r
} else if (v == VT_CMP) {
C67_MV(C67_compare_reg, r); // MV v,r v -> r
} else if (v == VT_JMP || v == VT_JMPI) {
t = v & 1;
C67_B_DISP(4); // Branch with constant displacement, skip over this branch, load, nop, load
C67_MVKL(r, t); // r=reg to load, 0 or 1 (do this while branching)
C67_NOP(4); // NOP 4
gsym(fc); // modifies other branches to branch here
C67_MVKL(r, t ^ 1); // r=reg to load, 0 or 1
} else if (v != r) {
C67_MV(v, r); // MV v,r v -> r
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_MV(v + 1, r + 1); // MV v,r v -> r
}
}
}
/* store register 'r' in lvalue 'v' */
void store(int r, SValue * v)
{
int fr, bt, ft, fc, size, t, element;
ft = v->type.t;
fc = v->c.ul;
fr = v->r & VT_VALMASK;
bt = ft & VT_BTYPE;
/* XXX: incorrect if float reg to reg */
if (bt == VT_LDOUBLE) {
error("long double not supported");
} else {
if (bt == VT_SHORT)
size = 2;
else if (bt == VT_BYTE)
size = 1;
else if (bt == VT_DOUBLE)
size = 8;
else
size = 4;
if ((v->r & VT_VALMASK) == VT_CONST) {
/* constant memory reference */
if (v->r & VT_SYM) {
greloc(cur_text_section, v->sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, v->sym, ind + 4, R_C60HI16);
}
C67_MVKL(C67_A0, fc); //r=reg to load, constant
C67_MVKH(C67_A0, fc); //r=reg to load, constant
if (size == 1)
C67_STB_PTR(r, C67_A0); // STB r, *A0
else if (size == 2)
C67_STH_PTR(r, C67_A0); // STH r, *A0
else if (size == 4 || size == 8)
C67_STW_PTR(r, C67_A0); // STW r, *A0
if (size == 8)
C67_STW_PTR_PRE_INC(r + 1, C67_A0, 1); // STW r, *+A0[1]
} else if ((v->r & VT_VALMASK) == VT_LOCAL) {
// check case of storing to passed argument that
// tcc thinks is on the stack but for C67 is
// passed as a reg. However it may have been
// saved to the stack, if that reg was required
// for a call to a child function
if (fc > 0) // argument ??
{
// walk through sizes and figure which param
int stack_pos = 8;
for (t = 0; t < NoCallArgsPassedOnStack; t++) {
if (fc == stack_pos)
break;
stack_pos += TranslateStackToReg[t];
}
// param has been pushed on stack, get it like a local var
fc = ParamLocOnStack[t] - 8;
}
if (size == 8)
element = 4;
else
element = size;
// divide offset in bytes to create word index
C67_MVKL(C67_A0, (fc / element) + 8 / element); //r=reg to load, constant
C67_MVKH(C67_A0, (fc / element) + 8 / element); //r=reg to load, constant
if (size == 1)
C67_STB_SP_A0(r); // STB r, SP[A0]
else if (size == 2)
C67_STH_SP_A0(r); // STH r, SP[A0]
else if (size == 4 || size == 8)
C67_STW_SP_A0(r); // STW r, SP[A0]
if (size == 8) {
C67_ADDK(1, C67_A0); // ADDK 1,A0
C67_STW_SP_A0(r + 1); // STW r, SP[A0]
}
} else {
if (size == 1)
C67_STB_PTR(r, fr); // STB r, *fr
else if (size == 2)
C67_STH_PTR(r, fr); // STH r, *fr
else if (size == 4 || size == 8)
C67_STW_PTR(r, fr); // STW r, *fr
if (size == 8) {
C67_STW_PTR_PRE_INC(r + 1, fr, 1); // STW r, *+fr[1]
}
}
}
}
/* 'is_jmp' is '1' if it is a jump */
static void gcall_or_jmp(int is_jmp)
{
int r;
Sym *sym;
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* constant case */
if (vtop->r & VT_SYM) {
/* relocation case */
// get add into A0, then start the jump B3
greloc(cur_text_section, vtop->sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, vtop->sym, ind + 4, R_C60HI16);
C67_MVKL(C67_A0, 0); //r=reg to load, constant
C67_MVKH(C67_A0, 0); //r=reg to load, constant
C67_IREG_B_REG(0, C67_CREG_ZERO, C67_A0); // B.S2x A0
if (is_jmp) {
C67_NOP(5); // simple jump, just put NOP
} else {
// Call, must load return address into B3 during delay slots
sym = get_sym_ref(&char_pointer_type, cur_text_section, ind + 12, 0); // symbol for return address
greloc(cur_text_section, sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, sym, ind + 4, R_C60HI16);
C67_MVKL(C67_B3, 0); //r=reg to load, constant
C67_MVKH(C67_B3, 0); //r=reg to load, constant
C67_NOP(3); // put remaining NOPs
}
} else {
/* put an empty PC32 relocation */
ALWAYS_ASSERT(FALSE);
}
} else {
/* otherwise, indirect call */
r = gv(RC_INT);
C67_IREG_B_REG(0, C67_CREG_ZERO, r); // B.S2x r
if (is_jmp) {
C67_NOP(5); // simple jump, just put NOP
} else {
// Call, must load return address into B3 during delay slots
sym = get_sym_ref(&char_pointer_type, cur_text_section, ind + 12, 0); // symbol for return address
greloc(cur_text_section, sym, ind, R_C60LO16); // rem the inst need to be patched
greloc(cur_text_section, sym, ind + 4, R_C60HI16);
C67_MVKL(C67_B3, 0); //r=reg to load, constant
C67_MVKH(C67_B3, 0); //r=reg to load, constant
C67_NOP(3); // put remaining NOPs
}
}
}
/* generate function call with address in (vtop->t, vtop->c) and free function
context. Stack entry is popped */
void gfunc_call(int nb_args)
{
int i, r, size = 0;
int args_sizes[NoCallArgsPassedOnStack];
if (nb_args > NoCallArgsPassedOnStack) {
error("more than 10 function params not currently supported");
// handle more than 10, put some on the stack
}
for (i = 0; i < nb_args; i++) {
if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
ALWAYS_ASSERT(FALSE);
} else if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
ALWAYS_ASSERT(FALSE);
} else {
/* simple type (currently always same size) */
/* XXX: implicit cast ? */
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
error("long long not supported");
} else if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
error("long double not supported");
} else if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
size = 8;
} else {
size = 4;
}
// put the parameter into the corresponding reg (pair)
r = gv(RC_C67_A4 << (2 * i));
// must put on stack because with 1 pass compiler , no way to tell
// if an up coming nested call might overwrite these regs
C67_PUSH(r);
if (size == 8) {
C67_STW_PTR_PRE_INC(r + 1, C67_SP, 3); // STW r, *+SP[3] (go back and put the other)
}
args_sizes[i] = size;
}
vtop--;
}
// POP all the params on the stack into registers for the
// immediate call (in reverse order)
for (i = nb_args - 1; i >= 0; i--) {
if (args_sizes[i] == 8)
C67_POP_DW(TREG_C67_A4 + i * 2);
else
C67_POP(TREG_C67_A4 + i * 2);
}
gcall_or_jmp(0);
vtop--;
}
// to be compatible with Code Composer for the C67
// the first 10 parameters must be passed in registers
// (pairs for 64 bits) starting wit; A4:A5, then B4:B5 and
// ending with B12:B13.
//
// When a call is made, if the caller has its parameters
// in regs A4-B13 these must be saved before/as the call
// parameters are loaded and restored upon return (or if/when needed).
/* generate function prolog of type 't' */
void gfunc_prolog(CType * func_type)
{
int addr, align, size, func_call, i;
Sym *sym;
CType *type;
sym = func_type->ref;
func_call = sym->r;
addr = 8;
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->type;
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
func_vc = addr;
addr += 4;
}
NoOfCurFuncArgs = 0;
/* define parameters */
while ((sym = sym->next) != NULL) {
type = &sym->type;
sym_push(sym->v & ~SYM_FIELD, type, VT_LOCAL | lvalue_type(type->t), addr);
size = type_size(type, &align);
size = (size + 3) & ~3;
// keep track of size of arguments so
// we can translate where tcc thinks they
// are on the stack into the appropriate reg
TranslateStackToReg[NoOfCurFuncArgs] = size;
NoOfCurFuncArgs++;
#ifdef FUNC_STRUCT_PARAM_AS_PTR
/* structs are passed as pointer */
if ((type->t & VT_BTYPE) == VT_STRUCT) {
size = 4;
}
#endif
addr += size;
}
func_ret_sub = 0;
/* pascal type call ? */
if (func_call == FUNC_STDCALL)
func_ret_sub = addr - 8;
C67_MV(C67_FP, C67_A0); // move FP -> A0
C67_MV(C67_SP, C67_FP); // move SP -> FP
// place all the args passed in regs onto the stack
loc = 0;
for (i = 0; i < NoOfCurFuncArgs; i++) {
ParamLocOnStack[i] = loc; // remember where the param is
loc += -8;
C67_PUSH(TREG_C67_A4 + i * 2);
if (TranslateStackToReg[i] == 8) {
C67_STW_PTR_PRE_INC(TREG_C67_A4 + i * 2 + 1, C67_SP, 3); // STW r, *+SP[1] (go back and put the other)
}
}
TotalBytesPushedOnStack = -loc;
func_sub_sp_offset = ind; // remember where we put the stack instruction
C67_ADDK(0, C67_SP); // ADDK.L2 loc,SP (just put zero temporarily)
C67_PUSH(C67_A0);
C67_PUSH(C67_B3);
}
/* generate function epilog */
void gfunc_epilog(void)
{
{
int local = (-loc + 7) & -8; // stack must stay aligned to 8 bytes for LDDW instr
C67_POP(C67_B3);
C67_NOP(4); // NOP wait for load
C67_IREG_B_REG(0, C67_CREG_ZERO, C67_B3); // B.S2 B3
C67_POP(C67_FP);
C67_ADDK(local, C67_SP); // ADDK.L2 loc,SP
C67_Adjust_ADDK((int *) (cur_text_section->data +
func_sub_sp_offset),
-local + TotalBytesPushedOnStack);
C67_NOP(3); // NOP
}
}
/* generate a jump to a label */
int gjmp(int t)
{
int ind1 = ind;
C67_MVKL(C67_A0, t); //r=reg to load, constant
C67_MVKH(C67_A0, t); //r=reg to load, constant
C67_IREG_B_REG(0, C67_CREG_ZERO, C67_A0); // [!R] B.S2x A0
C67_NOP(5);
return ind1;
}
/* generate a jump to a fixed address */
void gjmp_addr(int a)
{
Sym *sym;
// I guess this routine is used for relative short
// local jumps, for now just handle it as the general
// case
// define a label that will be relocated
sym = get_sym_ref(&char_pointer_type, cur_text_section, a, 0);
greloc(cur_text_section, sym, ind, R_C60LO16);
greloc(cur_text_section, sym, ind + 4, R_C60HI16);
gjmp(0); // place a zero there later the symbol will be added to it
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
int gtst(int inv, int t)
{
int ind1, n;
int v, *p;
v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
/* fast case : can jump directly since flags are set */
// C67 uses B2 sort of as flags register
ind1 = ind;
C67_MVKL(C67_A0, t); //r=reg to load, constant
C67_MVKH(C67_A0, t); //r=reg to load, constant
if (C67_compare_reg != TREG_EAX && // check if not already in a conditional test reg
C67_compare_reg != TREG_EDX &&
C67_compare_reg != TREG_ST0 && C67_compare_reg != C67_B2) {
C67_MV(C67_compare_reg, C67_B2);
C67_compare_reg = C67_B2;
}
C67_IREG_B_REG(C67_invert_test ^ inv, C67_compare_reg, C67_A0); // [!R] B.S2x A0
C67_NOP(5);
t = ind1; //return where we need to patch
} else if (v == VT_JMP || v == VT_JMPI) {
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
// I guess the idea is to traverse to the
// null at the end of the list and store t
// there
n = *p;
while (n != 0) {
p = (int *) (cur_text_section->data + n);
// extract 32 bit address from MVKH/MVKL
n = ((*p >> 7) & 0xffff);
n |= ((*(p + 1) >> 7) & 0xffff) << 16;
}
*p |= (t & 0xffff) << 7;
*(p + 1) |= ((t >> 16) & 0xffff) << 7;
t = vtop->c.i;
} else {
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->type.t)) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
// I think we need to get the value on the stack
// into a register, test it, and generate a branch
// return the address of the branch, so it can be
// later patched
v = gv(RC_INT); // get value into a reg
ind1 = ind;
C67_MVKL(C67_A0, t); //r=reg to load, constant
C67_MVKH(C67_A0, t); //r=reg to load, constant
if (v != TREG_EAX && // check if not already in a conditional test reg
v != TREG_EDX && v != TREG_ST0 && v != C67_B2) {
C67_MV(v, C67_B2);
v = C67_B2;
}
C67_IREG_B_REG(inv, v, C67_A0); // [!R] B.S2x A0
C67_NOP(5);
t = ind1; //return where we need to patch
ind1 = ind;
}
}
vtop--;
return t;
}
/* generate an integer binary operation */
void gen_opi(int op)
{
int r, fr, opc, t;
switch (op) {
case '+':
case TOK_ADDC1: /* add with carry generation */
opc = 0;
gen_op8:
// C67 can't do const compares, must load into a reg
// so just go to gv2 directly - tktk
if (op >= TOK_ULT && op <= TOK_GT)
gv2(RC_INT_BSIDE, RC_INT); // make sure r (src1) is on the B Side of CPU
else
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
C67_compare_reg = C67_B2;
if (op == TOK_LT) {
C67_CMPLT(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_GE) {
C67_CMPLT(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_GT) {
C67_CMPGT(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_LE) {
C67_CMPGT(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_EQ) {
C67_CMPEQ(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_NE) {
C67_CMPEQ(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_ULT) {
C67_CMPLTU(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_UGE) {
C67_CMPLTU(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_UGT) {
C67_CMPGTU(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_ULE) {
C67_CMPGTU(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == '+')
C67_ADD(fr, r); // ADD r,fr,r
else if (op == '-')
C67_SUB(fr, r); // SUB r,fr,r
else if (op == '&')
C67_AND(fr, r); // AND r,fr,r
else if (op == '|')
C67_OR(fr, r); // OR r,fr,r
else if (op == '^')
C67_XOR(fr, r); // XOR r,fr,r
else
ALWAYS_ASSERT(FALSE);
vtop--;
if (op >= TOK_ULT && op <= TOK_GT) {
vtop->r = VT_CMP;
vtop->c.i = op;
}
break;
case '-':
case TOK_SUBC1: /* sub with carry generation */
opc = 5;
goto gen_op8;
case TOK_ADDC2: /* add with carry use */
opc = 2;
goto gen_op8;
case TOK_SUBC2: /* sub with carry use */
opc = 3;
goto gen_op8;
case '&':
opc = 4;
goto gen_op8;
case '^':
opc = 6;
goto gen_op8;
case '|':
opc = 1;
goto gen_op8;
case '*':
case TOK_UMULL:
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
C67_MPYI(fr, r); // 32 bit bultiply fr,r,fr
C67_NOP(8); // NOP 8 for worst case
break;
case TOK_SHL:
gv2(RC_INT_BSIDE, RC_INT_BSIDE); // shift amount must be on same side as dst
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
C67_SHL(fr, r); // arithmetic/logical shift
break;
case TOK_SHR:
gv2(RC_INT_BSIDE, RC_INT_BSIDE); // shift amount must be on same side as dst
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
C67_SHRU(fr, r); // logical shift
break;
case TOK_SAR:
gv2(RC_INT_BSIDE, RC_INT_BSIDE); // shift amount must be on same side as dst
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
C67_SHR(fr, r); // arithmetic shift
break;
case '/':
t = TOK__divi;
call_func:
vswap();
/* call generic idiv function */
vpush_global_sym(&func_old_type, t);
vrott(3);
gfunc_call(2);
vpushi(0);
vtop->r = REG_IRET;
vtop->r2 = VT_CONST;
break;
case TOK_UDIV:
case TOK_PDIV:
t = TOK__divu;
goto call_func;
case '%':
t = TOK__remi;
goto call_func;
case TOK_UMOD:
t = TOK__remu;
goto call_func;
default:
opc = 7;
goto gen_op8;
}
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
/* XXX: need to use ST1 too */
void gen_opf(int op)
{
int ft, fc, fr, r;
if (op >= TOK_ULT && op <= TOK_GT)
gv2(RC_EDX, RC_EAX); // make sure src2 is on b side
else
gv2(RC_FLOAT, RC_FLOAT); // make sure src2 is on b side
ft = vtop->type.t;
fc = vtop->c.ul;
r = vtop->r;
fr = vtop[-1].r;
if ((ft & VT_BTYPE) == VT_LDOUBLE)
error("long doubles not supported");
if (op >= TOK_ULT && op <= TOK_GT) {
r = vtop[-1].r;
fr = vtop[0].r;
C67_compare_reg = C67_B2;
if (op == TOK_LT) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPLTDP(r, fr, C67_B2);
else
C67_CMPLTSP(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_GE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPLTDP(r, fr, C67_B2);
else
C67_CMPLTSP(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_GT) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPGTDP(r, fr, C67_B2);
else
C67_CMPGTSP(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_LE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPGTDP(r, fr, C67_B2);
else
C67_CMPGTSP(r, fr, C67_B2);
C67_invert_test = true;
} else if (op == TOK_EQ) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPEQDP(r, fr, C67_B2);
else
C67_CMPEQSP(r, fr, C67_B2);
C67_invert_test = false;
} else if (op == TOK_NE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPEQDP(r, fr, C67_B2);
else
C67_CMPEQSP(r, fr, C67_B2);
C67_invert_test = true;
} else {
ALWAYS_ASSERT(FALSE);
}
vtop->r = VT_CMP; // tell TCC that result is in "flags" actually B2
} else {
if (op == '+') {
if ((ft & VT_BTYPE) == VT_DOUBLE) {
C67_ADDDP(r, fr); // ADD fr,r,fr
C67_NOP(6);
} else {
C67_ADDSP(r, fr); // ADD fr,r,fr
C67_NOP(3);
}
vtop--;
} else if (op == '-') {
if ((ft & VT_BTYPE) == VT_DOUBLE) {
C67_SUBDP(r, fr); // SUB fr,r,fr
C67_NOP(6);
} else {
C67_SUBSP(r, fr); // SUB fr,r,fr
C67_NOP(3);
}
vtop--;
} else if (op == '*') {
if ((ft & VT_BTYPE) == VT_DOUBLE) {
C67_MPYDP(r, fr); // MPY fr,r,fr
C67_NOP(9);
} else {
C67_MPYSP(r, fr); // MPY fr,r,fr
C67_NOP(3);
}
vtop--;
} else if (op == '/') {
if ((ft & VT_BTYPE) == VT_DOUBLE) {
// must call intrinsic DP floating point divide
vswap();
/* call generic idiv function */
vpush_global_sym(&func_old_type, TOK__divd);
vrott(3);
gfunc_call(2);
vpushi(0);
vtop->r = REG_FRET;
vtop->r2 = REG_LRET;
} else {
// must call intrinsic SP floating point divide
vswap();
/* call generic idiv function */
vpush_global_sym(&func_old_type, TOK__divf);
vrott(3);
gfunc_call(2);
vpushi(0);
vtop->r = REG_FRET;
vtop->r2 = VT_CONST;
}
} else
ALWAYS_ASSERT(FALSE);
}
}
/* convert integers to fp 't' type. Must handle 'int', 'unsigned int'
and 'long long' cases. */
void gen_cvt_itof(int t)
{
int r;
gv(RC_INT);
r = vtop->r;
if ((t & VT_BTYPE) == VT_DOUBLE) {
if (t & VT_UNSIGNED)
C67_INTDPU(r, r);
else
C67_INTDP(r, r);
C67_NOP(4);
vtop->type.t = VT_DOUBLE;
} else {
if (t & VT_UNSIGNED)
C67_INTSPU(r, r);
else
C67_INTSP(r, r);
C67_NOP(3);
vtop->type.t = VT_FLOAT;
}
}
/* convert fp to int 't' type */
/* XXX: handle long long case */
void gen_cvt_ftoi(int t)
{
int r;
gv(RC_FLOAT);
r = vtop->r;
if (t != VT_INT)
error("long long not supported");
else {
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
C67_DPTRUNC(r, r);
C67_NOP(3);
} else {
C67_SPTRUNC(r, r);
C67_NOP(3);
}
vtop->type.t = VT_INT;
}
}
/* convert from one floating point type to another */
void gen_cvt_ftof(int t)
{
int r, r2;
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE &&
(t & VT_BTYPE) == VT_FLOAT) {
// convert double to float
gv(RC_FLOAT); // get it in a register pair
r = vtop->r;
C67_DPSP(r, r); // convert it to SP same register
C67_NOP(3);
vtop->type.t = VT_FLOAT;
vtop->r2 = VT_CONST; // set this as unused
} else if ((vtop->type.t & VT_BTYPE) == VT_FLOAT &&
(t & VT_BTYPE) == VT_DOUBLE) {
// convert float to double
gv(RC_FLOAT); // get it in a register
r = vtop->r;
if (r == TREG_EAX) { // make sure the paired reg is avail
r2 = get_reg(RC_ECX);
} else if (r == TREG_EDX) {
r2 = get_reg(RC_ST0);
} else {
ALWAYS_ASSERT(FALSE);
r2 = 0; /* avoid warning */
}
C67_SPDP(r, r); // convert it to DP same register
C67_NOP(1);
vtop->type.t = VT_DOUBLE;
vtop->r2 = r2; // set this as unused
} else {
ALWAYS_ASSERT(FALSE);
}
}
/* computed goto support */
void ggoto(void)
{
gcall_or_jmp(1);
vtop--;
}
/* end of X86 code generator */
/*************************************************************/
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/c67-gen.c | C | lgpl | 70,941 |
/*
* TCCPE.C - PE file output for the Tiny C Compiler
*
* Copyright (c) 2005-2007 grischka
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef TCC_TARGET_PE
#define ST_FN static
#define ST_DATA static
#define PUB_FN
#ifndef _WIN32
#define stricmp strcasecmp
#define strnicmp strncasecmp
#endif
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
#define PE_MERGE_DATA
// #define PE_PRINT_SECTIONS
/* ----------------------------------------------------------- */
#ifndef IMAGE_NT_SIGNATURE
/* ----------------------------------------------------------- */
/* definitions below are from winnt.h */
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
#pragma pack(push, 1)
typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
WORD e_magic; /* Magic number */
WORD e_cblp; /* Bytes on last page of file */
WORD e_cp; /* Pages in file */
WORD e_crlc; /* Relocations */
WORD e_cparhdr; /* Size of header in paragraphs */
WORD e_minalloc; /* Minimum extra paragraphs needed */
WORD e_maxalloc; /* Maximum extra paragraphs needed */
WORD e_ss; /* Initial (relative) SS value */
WORD e_sp; /* Initial SP value */
WORD e_csum; /* Checksum */
WORD e_ip; /* Initial IP value */
WORD e_cs; /* Initial (relative) CS value */
WORD e_lfarlc; /* File address of relocation table */
WORD e_ovno; /* Overlay number */
WORD e_res[4]; /* Reserved words */
WORD e_oemid; /* OEM identifier (for e_oeminfo) */
WORD e_oeminfo; /* OEM information; e_oemid specific */
WORD e_res2[10]; /* Reserved words */
DWORD e_lfanew; /* File address of new exe header */
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
#define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
#define SIZE_OF_NT_SIGNATURE 4
typedef struct _IMAGE_FILE_HEADER {
WORD Machine;
WORD NumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORD SizeOfOptionalHeader;
WORD Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
#define IMAGE_SIZEOF_FILE_HEADER 20
typedef struct _IMAGE_DATA_DIRECTORY {
DWORD VirtualAddress;
DWORD Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
typedef struct _IMAGE_OPTIONAL_HEADER {
/* Standard fields. */
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
/* NT additional fields. */
DWORD ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
DWORD SizeOfStackReserve;
DWORD SizeOfStackCommit;
DWORD SizeOfHeapReserve;
DWORD SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[16];
} IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER;
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
/* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
#define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
#define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
/* Section header format. */
#define IMAGE_SIZEOF_SHORT_NAME 8
typedef struct _IMAGE_SECTION_HEADER {
BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
union {
DWORD PhysicalAddress;
DWORD VirtualSize;
} Misc;
DWORD VirtualAddress;
DWORD SizeOfRawData;
DWORD PointerToRawData;
DWORD PointerToRelocations;
DWORD PointerToLinenumbers;
WORD NumberOfRelocations;
WORD NumberOfLinenumbers;
DWORD Characteristics;
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
#define IMAGE_SIZEOF_SECTION_HEADER 40
typedef struct _IMAGE_BASE_RELOCATION {
DWORD VirtualAddress;
DWORD SizeOfBlock;
// WORD TypeOffset[1];
} IMAGE_BASE_RELOCATION;
#define IMAGE_SIZEOF_BASE_RELOCATION 8
#define IMAGE_REL_BASED_ABSOLUTE 0
#define IMAGE_REL_BASED_HIGH 1
#define IMAGE_REL_BASED_LOW 2
#define IMAGE_REL_BASED_HIGHLOW 3
#define IMAGE_REL_BASED_HIGHADJ 4
#define IMAGE_REL_BASED_MIPS_JMPADDR 5
#define IMAGE_REL_BASED_SECTION 6
#define IMAGE_REL_BASED_REL32 7
#pragma pack(pop)
/* ----------------------------------------------------------- */
#endif /* ndef IMAGE_NT_SIGNATURE */
/* ----------------------------------------------------------- */
#pragma pack(push, 1)
struct pe_header
{
IMAGE_DOS_HEADER doshdr;
BYTE dosstub[0x40];
DWORD nt_sig;
IMAGE_FILE_HEADER filehdr;
IMAGE_OPTIONAL_HEADER opthdr;
};
struct pe_import_header {
DWORD first_entry;
DWORD time_date;
DWORD forwarder;
DWORD lib_name_offset;
DWORD first_thunk;
};
struct pe_export_header {
DWORD Characteristics;
DWORD TimeDateStamp;
DWORD Version;
DWORD Name;
DWORD Base;
DWORD NumberOfFunctions;
DWORD NumberOfNames;
DWORD AddressOfFunctions;
DWORD AddressOfNames;
DWORD AddressOfNameOrdinals;
};
struct pe_reloc_header {
DWORD offset;
DWORD size;
};
struct pe_rsrc_header {
struct _IMAGE_FILE_HEADER filehdr;
struct _IMAGE_SECTION_HEADER sectionhdr;
};
struct pe_rsrc_reloc {
DWORD offset;
DWORD size;
WORD type;
};
#pragma pack(pop)
/* ----------------------------------------------------------- */
ST_DATA struct pe_header pe_header = {
{
/* IMAGE_DOS_HEADER doshdr */
0x5A4D, /*WORD e_magic; Magic number */
0x0090, /*WORD e_cblp; Bytes on last page of file */
0x0003, /*WORD e_cp; Pages in file */
0x0000, /*WORD e_crlc; Relocations */
0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
0x0000, /*WORD e_ss; Initial (relative) SS value */
0x00B8, /*WORD e_sp; Initial SP value */
0x0000, /*WORD e_csum; Checksum */
0x0000, /*WORD e_ip; Initial IP value */
0x0000, /*WORD e_cs; Initial (relative) CS value */
0x0040, /*WORD e_lfarlc; File address of relocation table */
0x0000, /*WORD e_ovno; Overlay number */
{0,0,0,0}, /*WORD e_res[4]; Reserved words */
0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
{0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
0x00000080 /*DWORD e_lfanew; File address of new exe header */
},{
/* BYTE dosstub[0x40] */
/* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
},
0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
{
/* IMAGE_FILE_HEADER filehdr */
0x014C, /*WORD Machine; */
0x0003, /*WORD NumberOfSections; */
0x00000000, /*DWORD TimeDateStamp; */
0x00000000, /*DWORD PointerToSymbolTable; */
0x00000000, /*DWORD NumberOfSymbols; */
0x00E0, /*WORD SizeOfOptionalHeader; */
0x030F /*WORD Characteristics; */
},{
/* IMAGE_OPTIONAL_HEADER opthdr */
/* Standard fields. */
0x010B, /*WORD Magic; */
0x06, /*BYTE MajorLinkerVersion; */
0x00, /*BYTE MinorLinkerVersion; */
0x00000000, /*DWORD SizeOfCode; */
0x00000000, /*DWORD SizeOfInitializedData; */
0x00000000, /*DWORD SizeOfUninitializedData; */
0x00000000, /*DWORD AddressOfEntryPoint; */
0x00000000, /*DWORD BaseOfCode; */
0x00000000, /*DWORD BaseOfData; */
/* NT additional fields. */
0x00400000, /*DWORD ImageBase; */
0x00001000, /*DWORD SectionAlignment; */
0x00000200, /*DWORD FileAlignment; */
0x0004, /*WORD MajorOperatingSystemVersion; */
0x0000, /*WORD MinorOperatingSystemVersion; */
0x0000, /*WORD MajorImageVersion; */
0x0000, /*WORD MinorImageVersion; */
0x0004, /*WORD MajorSubsystemVersion; */
0x0000, /*WORD MinorSubsystemVersion; */
0x00000000, /*DWORD Win32VersionValue; */
0x00000000, /*DWORD SizeOfImage; */
0x00000200, /*DWORD SizeOfHeaders; */
0x00000000, /*DWORD CheckSum; */
0x0002, /*WORD Subsystem; */
0x0000, /*WORD DllCharacteristics; */
0x00100000, /*DWORD SizeOfStackReserve; */
0x00001000, /*DWORD SizeOfStackCommit; */
0x00100000, /*DWORD SizeOfHeapReserve; */
0x00001000, /*DWORD SizeOfHeapCommit; */
0x00000000, /*DWORD LoaderFlags; */
0x00000010, /*DWORD NumberOfRvaAndSizes; */
/* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
{{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
}};
/* ------------------------------------------------------------- */
/* internal temporary structures */
/*
#define IMAGE_SCN_CNT_CODE 0x00000020
#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
#define IMAGE_SCN_MEM_SHARED 0x10000000
#define IMAGE_SCN_MEM_EXECUTE 0x20000000
#define IMAGE_SCN_MEM_READ 0x40000000
#define IMAGE_SCN_MEM_WRITE 0x80000000
*/
enum {
sec_text = 0,
sec_data ,
sec_bss ,
sec_idata ,
sec_other ,
sec_rsrc ,
sec_stab ,
sec_reloc ,
sec_last
};
ST_DATA DWORD pe_sec_flags[] = {
0x60000020, /* ".text" , */
0xC0000040, /* ".data" , */
0xC0000080, /* ".bss" , */
0x40000040, /* ".idata" , */
0xE0000060, /* < other > , */
0x40000040, /* ".rsrc" , */
0x42000802, /* ".stab" , */
0x42000040, /* ".reloc" , */
};
struct section_info {
int cls, ord;
char name[32];
DWORD sh_addr;
DWORD sh_size;
DWORD sh_flags;
unsigned char *data;
DWORD data_size;
IMAGE_SECTION_HEADER ish;
};
struct import_symbol {
int sym_index;
int iat_index;
int thk_offset;
};
struct pe_import_info {
int dll_index;
int sym_count;
struct import_symbol **symbols;
};
struct pe_info {
TCCState *s1;
Section *reloc;
Section *thunk;
const char *filename;
int type;
DWORD sizeofheaders;
DWORD imagebase;
DWORD start_addr;
DWORD imp_offs;
DWORD imp_size;
DWORD iat_offs;
DWORD iat_size;
DWORD exp_offs;
DWORD exp_size;
struct section_info *sec_info;
int sec_count;
struct pe_import_info **imp_info;
int imp_count;
};
/* ------------------------------------------------------------- */
#define PE_NUL 0
#define PE_DLL 1
#define PE_GUI 2
#define PE_EXE 3
void error_noabort(const char *, ...);
#ifdef _WIN32
void dbg_printf (const char *fmt, ...)
{
char buffer[4000];
va_list arg;
int x;
va_start(arg, fmt);
x = vsprintf (buffer, fmt, arg);
strcpy(buffer+x, "\n");
OutputDebugString(buffer);
}
#endif
/* --------------------------------------------*/
ST_FN const char* get_alt_symbol(char *buffer, const char *symbol)
{
const char *p;
p = strrchr(symbol, '@');
if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */
strcpy(buffer, symbol+1)[p-symbol-1] = 0;
} else if (symbol[0] != '_') { /* try non-ansi function */
buffer[0] = '_', strcpy(buffer + 1, symbol);
} else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */
strcpy(buffer, symbol + 6);
} else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */
strcpy(buffer, symbol + 6);
} else {
return symbol;
}
return buffer;
}
ST_FN int pe_find_import(TCCState * s1, const char *symbol)
{
char buffer[200];
const char *s;
int sym_index, n = 0;
do {
s = n ? get_alt_symbol(buffer, symbol) : symbol;
sym_index = find_elf_sym(s1->dynsymtab_section, s);
// printf("find %d %s\n", sym_index, s);
} while (0 == sym_index && ++n < 2);
return sym_index;
}
#if defined _WIN32 || defined __CYGWIN__
#ifdef __CYGWIN__
# include <dlfcn.h>
# define LoadLibrary(s) dlopen(s, RTLD_NOW)
# define GetProcAddress(h,s) dlsym(h, s)
#else
# define dlclose(h) FreeLibrary(h)
#endif
/* for the -run option: dynamically load symbol from dll */
void *resolve_sym(struct TCCState *s1, const char *symbol, int type)
{
char buffer[100];
int sym_index, dll_index;
void *addr, **m;
DLLReference *dllref;
sym_index = pe_find_import(s1, symbol);
if (0 == sym_index)
return NULL;
dll_index = ((Elf32_Sym *)s1->dynsymtab_section->data + sym_index)->st_value;
dllref = s1->loaded_dlls[dll_index-1];
if ( !dllref->handle )
{
dllref->handle = LoadLibrary(dllref->name);
}
addr = GetProcAddress(dllref->handle, symbol);
if (NULL == addr)
addr = GetProcAddress(dllref->handle, get_alt_symbol(buffer, symbol));
if (addr && STT_OBJECT == type) {
/* need to return a pointer to the address for data objects */
m = (void**)tcc_malloc(sizeof addr), *m = addr, addr = m;
#ifdef MEM_DEBUG
/* yep, we don't free it */
mem_cur_size -= sizeof (void*);
#endif
}
return addr;
}
#endif
/*----------------------------------------------------------------------------*/
ST_FN int dynarray_assoc(void **pp, int n, int key)
{
int i;
for (i = 0; i < n; ++i, ++pp)
if (key == **(int **) pp)
return i;
return -1;
}
#if 0
ST_FN DWORD umin(DWORD a, DWORD b)
{
return a < b ? a : b;
}
#endif
ST_FN DWORD umax(DWORD a, DWORD b)
{
return a < b ? b : a;
}
ST_FN void pe_fpad(FILE *fp, DWORD new_pos)
{
DWORD pos = ftell(fp);
while (++pos <= new_pos)
fputc(0, fp);
}
ST_FN DWORD pe_file_align(DWORD n)
{
return (n + (0x200 - 1)) & ~(0x200 - 1);
}
ST_FN DWORD pe_virtual_align(DWORD n)
{
return (n + (0x1000 - 1)) & ~(0x1000 - 1);
}
ST_FN void pe_align_section(Section *s, int a)
{
int i = s->data_offset & (a-1);
if (i)
section_ptr_add(s, a - i);
}
ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size)
{
pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr;
pe_header.opthdr.DataDirectory[dir].Size = size;
}
/*----------------------------------------------------------------------------*/
ST_FN int pe_write(struct pe_info *pe)
{
int i;
FILE *op;
DWORD file_offset, r;
op = fopen(pe->filename, "wb");
if (NULL == op) {
error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
return 1;
}
pe->sizeofheaders = pe_file_align(
sizeof pe_header
+ pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
);
file_offset = pe->sizeofheaders;
pe_fpad(op, file_offset);
if (2 == pe->s1->verbose)
printf("-------------------------------"
"\n virt file size section" "\n");
for (i = 0; i < pe->sec_count; ++i) {
struct section_info *si = pe->sec_info + i;
const char *sh_name = si->name;
unsigned long addr = si->sh_addr - pe->imagebase;
unsigned long size = si->sh_size;
IMAGE_SECTION_HEADER *psh = &si->ish;
if (2 == pe->s1->verbose)
printf("%6lx %6lx %6lx %s\n",
addr, file_offset, size, sh_name);
switch (si->cls) {
case sec_text:
pe_header.opthdr.BaseOfCode = addr;
pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr;
break;
case sec_data:
pe_header.opthdr.BaseOfData = addr;
break;
case sec_bss:
break;
case sec_reloc:
pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
break;
case sec_rsrc:
pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
break;
case sec_stab:
break;
}
if (pe->thunk == pe->s1->sections[si->ord]) {
if (pe->imp_size) {
pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT,
pe->imp_offs + addr, pe->imp_size);
pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT,
pe->iat_offs + addr, pe->iat_size);
}
if (pe->exp_size) {
pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT,
pe->exp_offs + addr, pe->exp_size);
}
}
strcpy((char*)psh->Name, sh_name);
psh->Characteristics = pe_sec_flags[si->cls];
psh->VirtualAddress = addr;
psh->Misc.VirtualSize = size;
pe_header.opthdr.SizeOfImage =
umax(pe_virtual_align(size + addr), pe_header.opthdr.SizeOfImage);
if (si->data_size) {
psh->PointerToRawData = r = file_offset;
fwrite(si->data, 1, si->data_size, op);
file_offset = pe_file_align(file_offset + si->data_size);
psh->SizeOfRawData = file_offset - r;
pe_fpad(op, file_offset);
}
}
// pe_header.filehdr.TimeDateStamp = time(NULL);
pe_header.filehdr.NumberOfSections = pe->sec_count;
pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
pe_header.opthdr.ImageBase = pe->imagebase;
if (PE_DLL == pe->type)
pe_header.filehdr.Characteristics = 0x230E;
else if (PE_GUI != pe->type)
pe_header.opthdr.Subsystem = 3;
fseek(op, SEEK_SET, 0);
fwrite(&pe_header, 1, sizeof pe_header, op);
for (i = 0; i < pe->sec_count; ++i)
fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
fclose (op);
if (2 == pe->s1->verbose)
printf("-------------------------------\n");
if (pe->s1->verbose)
printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
return 0;
}
/*----------------------------------------------------------------------------*/
ST_FN struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
{
int i;
int dll_index;
struct pe_import_info *p;
struct import_symbol *s;
dll_index = ((Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index)->st_value;
if (0 == dll_index)
return NULL;
i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
if (-1 != i) {
p = pe->imp_info[i];
goto found_dll;
}
p = tcc_mallocz(sizeof *p);
p->dll_index = dll_index;
dynarray_add((void***)&pe->imp_info, &pe->imp_count, p);
found_dll:
i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
if (-1 != i)
return p->symbols[i];
s = tcc_mallocz(sizeof *s);
dynarray_add((void***)&p->symbols, &p->sym_count, s);
s->sym_index = sym_index;
return s;
}
/*----------------------------------------------------------------------------*/
ST_FN void pe_build_imports(struct pe_info *pe)
{
int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
int ndlls = pe->imp_count;
for (sym_cnt = i = 0; i < ndlls; ++i)
sym_cnt += pe->imp_info[i]->sym_count;
if (0 == sym_cnt)
return;
pe_align_section(pe->thunk, 16);
pe->imp_offs = dll_ptr = pe->thunk->data_offset;
pe->imp_size = (ndlls + 1) * sizeof(struct pe_import_header);
pe->iat_offs = dll_ptr + pe->imp_size;
pe->iat_size = (sym_cnt + ndlls) * sizeof(DWORD);
section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
thk_ptr = pe->iat_offs;
ent_ptr = pe->iat_offs + pe->iat_size;
for (i = 0; i < pe->imp_count; ++i) {
struct pe_import_header *hdr;
int k, n, v;
struct pe_import_info *p = pe->imp_info[i];
const char *name = pe->s1->loaded_dlls[p->dll_index-1]->name;
/* put the dll name into the import header */
v = put_elf_str(pe->thunk, name);
hdr = (struct pe_import_header*)(pe->thunk->data + dll_ptr);
hdr->first_thunk = thk_ptr + rva_base;
hdr->first_entry = ent_ptr + rva_base;
hdr->lib_name_offset = v + rva_base;
for (k = 0, n = p->sym_count; k <= n; ++k) {
if (k < n) {
DWORD iat_index = p->symbols[k]->iat_index;
int sym_index = p->symbols[k]->sym_index;
Elf32_Sym *imp_sym = (Elf32_Sym *)pe->s1->dynsymtab_section->data + sym_index;
Elf32_Sym *org_sym = (Elf32_Sym *)symtab_section->data + iat_index;
const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
org_sym->st_value = thk_ptr;
org_sym->st_shndx = pe->thunk->sh_num;
v = pe->thunk->data_offset + rva_base;
section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
put_elf_str(pe->thunk, name);
} else {
v = 0; /* last entry is zero */
}
*(DWORD*)(pe->thunk->data+thk_ptr) =
*(DWORD*)(pe->thunk->data+ent_ptr) = v;
thk_ptr += sizeof (DWORD);
ent_ptr += sizeof (DWORD);
}
dll_ptr += sizeof(struct pe_import_header);
dynarray_reset(&p->symbols, &p->sym_count);
}
dynarray_reset(&pe->imp_info, &pe->imp_count);
}
/* ------------------------------------------------------------- */
/*
For now only functions are exported. Export of data
would work, but import requires compiler support to
do an additional indirection.
For instance:
__declspec(dllimport) extern int something;
needs to be translated to:
*(int*)something
*/
ST_FN int sym_cmp(const void *va, const void *vb)
{
const char *ca = ((const char **)va)[1];
const char *cb = ((const char **)vb)[1];
return strcmp(ca, cb);
}
ST_FN void pe_build_exports(struct pe_info *pe)
{
Elf32_Sym *sym;
int sym_index, sym_end;
DWORD rva_base, func_o, name_o, ord_o, str_o;
struct pe_export_header *hdr;
int sym_count, n, ord, *sorted, *sp;
FILE *op;
char buf[MAX_PATH];
const char *dllname;
const char *name;
rva_base = pe->thunk->sh_addr - pe->imagebase;
sym_count = 0, n = 1, sorted = NULL, op = NULL;
sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
for (sym_index = 1; sym_index < sym_end; ++sym_index) {
sym = (Elf32_Sym*)symtab_section->data + sym_index;
name = symtab_section->link->data + sym->st_name;
if ((sym->st_other & 1)
/* export only symbols from actually written sections */
&& pe->s1->sections[sym->st_shndx]->sh_addr) {
dynarray_add((void***)&sorted, &sym_count, (void*)n);
dynarray_add((void***)&sorted, &sym_count, (void*)name);
}
++n;
#if 0
if (sym->st_other & 1)
printf("export: %s\n", name);
if (sym->st_other & 2)
printf("stdcall: %s\n", name);
#endif
}
if (0 == sym_count)
return;
sym_count /= 2;
qsort (sorted, sym_count, 2 * sizeof sorted[0], sym_cmp);
pe_align_section(pe->thunk, 16);
dllname = tcc_basename(pe->filename);
pe->exp_offs = pe->thunk->data_offset;
func_o = pe->exp_offs + sizeof(struct pe_export_header);
name_o = func_o + sym_count * sizeof (DWORD);
ord_o = name_o + sym_count * sizeof (DWORD);
str_o = ord_o + sym_count * sizeof(WORD);
hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
hdr->Characteristics = 0;
hdr->Base = 1;
hdr->NumberOfFunctions = sym_count;
hdr->NumberOfNames = sym_count;
hdr->AddressOfFunctions = func_o + rva_base;
hdr->AddressOfNames = name_o + rva_base;
hdr->AddressOfNameOrdinals = ord_o + rva_base;
hdr->Name = str_o + rva_base;
put_elf_str(pe->thunk, dllname);
#if 1
/* automatically write exports to <output-filename>.def */
strcpy(buf, pe->filename);
strcpy(tcc_fileextension(buf), ".def");
op = fopen(buf, "w");
if (NULL == op) {
error_noabort("could not create '%s': %s", buf, strerror(errno));
} else {
fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
if (pe->s1->verbose)
printf("<- %s (%d symbols)\n", buf, sym_count);
}
#endif
for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2)
{
sym_index = sp[0], name = (const char *)sp[1];
/* insert actual address later in pe_relocate_rva */
put_elf_reloc(symtab_section, pe->thunk,
func_o, R_386_RELATIVE, sym_index);
*(DWORD*)(pe->thunk->data + name_o)
= pe->thunk->data_offset + rva_base;
*(WORD*)(pe->thunk->data + ord_o)
= ord;
put_elf_str(pe->thunk, name);
func_o += sizeof (DWORD);
name_o += sizeof (DWORD);
ord_o += sizeof (WORD);
if (op)
fprintf(op, "%s\n", name);
}
pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
tcc_free(sorted);
}
/* ------------------------------------------------------------- */
ST_FN void pe_build_reloc (struct pe_info *pe)
{
DWORD offset, block_ptr, addr;
int count, i;
Elf32_Rel *rel, *rel_end;
Section *s = NULL, *sr;
offset = addr = block_ptr = count = i = 0;
rel = rel_end = NULL;
for(;;) {
if (rel < rel_end) {
int type = ELF32_R_TYPE(rel->r_info);
addr = rel->r_offset + s->sh_addr;
++ rel;
if (type != R_386_32)
continue;
if (count == 0) { /* new block */
block_ptr = pe->reloc->data_offset;
section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header));
offset = addr & 0xFFFFFFFF<<12;
}
if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */
WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD));
*wp = addr | IMAGE_REL_BASED_HIGHLOW<<12;
++count;
continue;
}
-- rel;
} else if (i < pe->sec_count) {
sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc;
if (sr) {
rel = (Elf32_Rel *)sr->data;
rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
}
continue;
}
if (count) {
/* store the last block and ready for a new one */
struct pe_reloc_header *hdr;
if (count & 1) /* align for DWORDS */
section_ptr_add(pe->reloc, sizeof(WORD)), ++count;
hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr);
hdr -> offset = offset - pe->imagebase;
hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header);
count = 0;
}
if (rel >= rel_end)
break;
}
}
/* ------------------------------------------------------------- */
ST_FN int pe_section_class(Section *s)
{
int type, flags;
const char *name;
type = s->sh_type;
flags = s->sh_flags;
name = s->name;
if (flags & SHF_ALLOC) {
if (type == SHT_PROGBITS) {
if (flags & SHF_EXECINSTR)
return sec_text;
if (flags & SHF_WRITE)
return sec_data;
if (0 == strcmp(name, ".rsrc"))
return sec_rsrc;
if (0 == strcmp(name, ".iedat"))
return sec_idata;
return sec_other;
} else if (type == SHT_NOBITS) {
if (flags & SHF_WRITE)
return sec_bss;
}
} else {
if (0 == strcmp(name, ".reloc"))
return sec_reloc;
if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */
return sec_stab;
}
return -1;
}
ST_FN int pe_assign_addresses (struct pe_info *pe)
{
int i, k, o, c;
DWORD addr;
int *section_order;
struct section_info *si;
Section *s;
// pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
for (o = k = 0 ; k < sec_last; ++k) {
for (i = 1; i < pe->s1->nb_sections; ++i) {
s = pe->s1->sections[i];
if (k == pe_section_class(s)) {
// printf("%s %d\n", s->name, k);
s->sh_addr = pe->imagebase;
section_order[o++] = i;
}
}
}
pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
addr = pe->imagebase + 1;
for (i = 0; i < o; ++i)
{
k = section_order[i];
s = pe->s1->sections[k];
c = pe_section_class(s);
si = &pe->sec_info[pe->sec_count];
#ifdef PE_MERGE_DATA
if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
/* append .bss to .data */
s->sh_addr = addr = ((addr-1) | 15) + 1;
addr += s->data_offset;
si[-1].sh_size = addr - si[-1].sh_addr;
continue;
}
#endif
strcpy(si->name, s->name);
si->cls = c;
si->ord = k;
si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
si->sh_flags = s->sh_flags;
if (c == sec_data && NULL == pe->thunk)
pe->thunk = s;
if (s == pe->thunk) {
pe_build_imports(pe);
pe_build_exports(pe);
}
if (c == sec_reloc)
pe_build_reloc (pe);
if (s->data_offset)
{
if (s->sh_type != SHT_NOBITS) {
si->data = s->data;
si->data_size = s->data_offset;
}
addr += s->data_offset;
si->sh_size = s->data_offset;
++pe->sec_count;
}
// printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
}
#if 0
for (i = 1; i < pe->s1->nb_sections; ++i) {
Section *s = pe->s1->sections[i];
int type = s->sh_type;
int flags = s->sh_flags;
printf("section %-16s %-10s %5x %s,%s,%s\n",
s->name,
type == SHT_PROGBITS ? "progbits" :
type == SHT_NOBITS ? "nobits" :
type == SHT_SYMTAB ? "symtab" :
type == SHT_STRTAB ? "strtab" :
type == SHT_REL ? "rel" : "???",
s->data_offset,
flags & SHF_ALLOC ? "alloc" : "",
flags & SHF_WRITE ? "write" : "",
flags & SHF_EXECINSTR ? "exec" : ""
);
}
pe->s1->verbose = 2;
#endif
tcc_free(section_order);
return 0;
}
/* ------------------------------------------------------------- */
ST_FN void pe_relocate_rva (struct pe_info *pe, Section *s)
{
Section *sr = s->reloc;
Elf32_Rel *rel, *rel_end;
rel_end = (Elf32_Rel *)(sr->data + sr->data_offset);
for(rel = (Elf32_Rel *)sr->data; rel < rel_end; rel++)
if (ELF32_R_TYPE(rel->r_info) == R_386_RELATIVE) {
int sym_index = ELF32_R_SYM(rel->r_info);
DWORD addr = s->sh_addr;
if (sym_index) {
Elf32_Sym *sym = (Elf32_Sym *)symtab_section->data + sym_index;
addr = sym->st_value;
}
*(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase;
}
}
/*----------------------------------------------------------------------------*/
ST_FN int pe_check_symbols(struct pe_info *pe)
{
Elf32_Sym *sym;
int sym_index, sym_end;
int ret = 0;
pe_align_section(text_section, 8);
sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
for (sym_index = 1; sym_index < sym_end; ++sym_index) {
sym = (Elf32_Sym*)symtab_section->data + sym_index;
if (sym->st_shndx == SHN_UNDEF) {
const char *name = symtab_section->link->data + sym->st_name;
unsigned type = ELF32_ST_TYPE(sym->st_info);
int imp_sym = pe_find_import(pe->s1, name);
struct import_symbol *is;
if (0 == imp_sym)
goto not_found;
is = pe_add_import(pe, imp_sym);
if (!is)
goto not_found;
if (type == STT_FUNC) {
unsigned long offset = is->thk_offset;
if (offset) {
/* got aliased symbol, like stricmp and _stricmp */
} else {
char buffer[100];
offset = text_section->data_offset;
/* add the 'jmp IAT[x]' instruction */
*(WORD*)section_ptr_add(text_section, 8) = 0x25FF;
/* add a helper symbol, will be patched later in
pe_build_imports */
sprintf(buffer, "IAT.%s", name);
is->iat_index = put_elf_sym(
symtab_section, 0, sizeof(DWORD),
ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT),
0, SHN_UNDEF, buffer);
put_elf_reloc(symtab_section, text_section,
offset + 2, R_386_32, is->iat_index);
is->thk_offset = offset;
}
/* tcc_realloc might have altered sym's address */
sym = (Elf32_Sym*)symtab_section->data + sym_index;
/* patch the original symbol */
sym->st_value = offset;
sym->st_shndx = text_section->sh_num;
sym->st_other &= ~1; /* do not export */
continue;
}
if (type == STT_OBJECT) { /* data, ptr to that should be */
if (0 == is->iat_index) {
/* original symbol will be patched later in pe_build_imports */
is->iat_index = sym_index;
continue;
}
}
not_found:
error_noabort("undefined symbol '%s'", name);
ret = 1;
} else if (pe->s1->rdynamic
&& ELF32_ST_BIND(sym->st_info) != STB_LOCAL) {
/* if -rdynamic option, then export all non local symbols */
sym->st_other |= 1;
}
}
return ret;
}
/*----------------------------------------------------------------------------*/
#ifdef PE_PRINT_SECTIONS
ST_FN void pe_print_section(FILE * f, Section * s)
{
/* just if you'r curious */
BYTE *p, *e, b;
int i, n, l, m;
p = s->data;
e = s->data + s->data_offset;
l = e - p;
fprintf(f, "section \"%s\"", s->name);
if (s->link)
fprintf(f, "\nlink \"%s\"", s->link->name);
if (s->reloc)
fprintf(f, "\nreloc \"%s\"", s->reloc->name);
fprintf(f, "\nv_addr %08X", s->sh_addr);
fprintf(f, "\ncontents %08X", l);
fprintf(f, "\n\n");
if (s->sh_type == SHT_NOBITS)
return;
if (0 == l)
return;
if (s->sh_type == SHT_SYMTAB)
m = sizeof(Elf32_Sym);
if (s->sh_type == SHT_REL)
m = sizeof(Elf32_Rel);
else
m = 16;
fprintf(f, "%-8s", "offset");
for (i = 0; i < m; ++i)
fprintf(f, " %02x", i);
n = 56;
if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_REL) {
const char *fields1[] = {
"name",
"value",
"size",
"bind",
"type",
"other",
"shndx",
NULL
};
const char *fields2[] = {
"offs",
"type",
"symb",
NULL
};
const char **p;
if (s->sh_type == SHT_SYMTAB)
p = fields1, n = 106;
else
p = fields2, n = 58;
for (i = 0; p[i]; ++i)
fprintf(f, "%6s", p[i]);
fprintf(f, " symbol");
}
fprintf(f, "\n");
for (i = 0; i < n; ++i)
fprintf(f, "-");
fprintf(f, "\n");
for (i = 0; i < l;)
{
fprintf(f, "%08X", i);
for (n = 0; n < m; ++n) {
if (n + i < l)
fprintf(f, " %02X", p[i + n]);
else
fprintf(f, " ");
}
if (s->sh_type == SHT_SYMTAB) {
Elf32_Sym *sym = (Elf32_Sym *) (p + i);
const char *name = s->link->data + sym->st_name;
fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"",
sym->st_name,
sym->st_value,
sym->st_size,
ELF32_ST_BIND(sym->st_info),
ELF32_ST_TYPE(sym->st_info),
sym->st_other, sym->st_shndx, name);
} else if (s->sh_type == SHT_REL) {
Elf32_Rel *rel = (Elf32_Rel *) (p + i);
Elf32_Sym *sym =
(Elf32_Sym *) s->link->data + ELF32_R_SYM(rel->r_info);
const char *name = s->link->link->data + sym->st_name;
fprintf(f, " %04X %02X %04X \"%s\"",
rel->r_offset,
ELF32_R_TYPE(rel->r_info),
ELF32_R_SYM(rel->r_info), name);
} else {
fprintf(f, " ");
for (n = 0; n < m; ++n) {
if (n + i < l) {
b = p[i + n];
if (b < 32 || b >= 127)
b = '.';
fprintf(f, "%c", b);
}
}
}
i += m;
fprintf(f, "\n");
}
fprintf(f, "\n\n");
}
ST_FN void pe_print_sections(TCCState *s1, const char *fname)
{
Section *s;
FILE *f;
int i;
f = fopen(fname, "wt");
for (i = 1; i < s1->nb_sections; ++i) {
s = s1->sections[i];
pe_print_section(f, s);
}
pe_print_section(f, s1->dynsymtab_section);
fclose(f);
}
#endif
/* -------------------------------------------------------------
* This is for compiled windows resources in 'coff' format
* as generated by 'windres.exe -O coff ...'.
*/
PUB_FN int pe_test_res_file(void *v, int size)
{
struct pe_rsrc_header *p = (struct pe_rsrc_header *)v;
return
size >= IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_SHORT_NAME /* = 28 */
&& p->filehdr.Machine == 0x014C
&& 1 == p->filehdr.NumberOfSections
&& 0 == strcmp(p->sectionhdr.Name, ".rsrc")
;
}
ST_FN int read_n(int fd, void *ptr, unsigned size)
{
return size == read(fd, ptr, size);
}
PUB_FN int pe_load_res_file(TCCState *s1, int fd)
{
struct pe_rsrc_header hdr;
Section *rsrc_section;
int i, ret = -1;
BYTE *ptr;
lseek (fd, 0, SEEK_SET);
if (!read_n(fd, &hdr, sizeof hdr))
goto quit;
if (!pe_test_res_file(&hdr, sizeof hdr))
goto quit;
rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC);
ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData);
lseek (fd, hdr.sectionhdr.PointerToRawData, SEEK_SET);
if (!read_n(fd, ptr, hdr.sectionhdr.SizeOfRawData))
goto quit;
lseek (fd, hdr.sectionhdr.PointerToRelocations, SEEK_SET);
for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i)
{
struct pe_rsrc_reloc rel;
if (!read_n(fd, &rel, sizeof rel))
goto quit;
// printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type);
if (rel.type != 7) /* DIR32NB */
goto quit;
put_elf_reloc(symtab_section, rsrc_section,
rel.offset, R_386_RELATIVE, 0);
}
ret = 0;
quit:
if (ret)
error_noabort("unrecognized resource file format");
return ret;
}
/* ------------------------------------------------------------- */
ST_FN char *trimfront(char *p)
{
while (*p && (unsigned char)*p <= ' ')
++p;
return p;
}
ST_FN char *trimback(char *a, char *e)
{
while (e > a && (unsigned char)e[-1] <= ' ')
--e;
*e = 0;;
return a;
}
ST_FN char *get_line(char *line, int size, FILE *fp)
{
if (NULL == fgets(line, size, fp))
return NULL;
trimback(line, strchr(line, 0));
return trimfront(line);
}
/* ------------------------------------------------------------- */
PUB_FN int pe_load_def_file(TCCState *s1, int fd)
{
DLLReference *dllref;
int state = 0, ret = -1;
char line[400], dllname[80], *p;
FILE *fp = fdopen(dup(fd), "rb");
if (NULL == fp)
goto quit;
for (;;) {
p = get_line(line, sizeof line, fp);
if (NULL == p)
break;
if (0 == *p || ';' == *p)
continue;
switch (state) {
case 0:
if (0 != strnicmp(p, "LIBRARY", 7))
goto quit;
strcpy(dllname, trimfront(p+7));
++state;
continue;
case 1:
if (0 != stricmp(p, "EXPORTS"))
goto quit;
++state;
continue;
case 2:
dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
strcpy(dllref->name, dllname);
dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
++state;
default:
add_elf_sym(s1->dynsymtab_section,
s1->nb_loaded_dlls, 0,
ELF32_ST_INFO(STB_GLOBAL, STT_FUNC), 0,
text_section->sh_num, p);
continue;
}
}
ret = 0;
quit:
if (fp)
fclose(fp);
if (ret)
error_noabort("unrecognized export definition file format");
return ret;
}
/* ------------------------------------------------------------- */
ST_FN void pe_add_runtime_ex(TCCState *s1, struct pe_info *pe)
{
const char *start_symbol;
unsigned long addr = 0;
int pe_type = 0;
if (find_elf_sym(symtab_section, "_WinMain@16"))
pe_type = PE_GUI;
else
if (TCC_OUTPUT_DLL == s1->output_type) {
pe_type = PE_DLL;
/* need this for 'tccelf.c:relocate_section()' */
s1->output_type = TCC_OUTPUT_EXE;
}
start_symbol =
TCC_OUTPUT_MEMORY == s1->output_type
? PE_GUI == pe_type ? "_runwinmain" : NULL
: PE_DLL == pe_type ? "__dllstart@12"
: PE_GUI == pe_type ? "_winstart" : "_start"
;
/* grab the startup code from libtcc1 */
if (start_symbol)
add_elf_sym(symtab_section,
0, 0,
ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
SHN_UNDEF, start_symbol);
if (0 == s1->nostdlib) {
tcc_add_library(s1, "tcc1");
#ifdef __CYGWIN__
tcc_add_library(s1, "cygwin1");
#else
tcc_add_library(s1, "msvcrt");
#endif
tcc_add_library(s1, "kernel32");
if (PE_DLL == pe_type || PE_GUI == pe_type) {
tcc_add_library(s1, "user32");
tcc_add_library(s1, "gdi32");
}
}
if (start_symbol) {
addr = (unsigned long)tcc_get_symbol_err(s1, start_symbol);
if (s1->output_type == TCC_OUTPUT_MEMORY && addr)
/* for -run GUI's, put '_runwinmain' instead of 'main' */
add_elf_sym(symtab_section,
addr, 0,
ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
text_section->sh_num, "main");
}
if (pe) {
pe->type = pe_type;
pe->start_addr = addr;
}
}
PUB_FN void pe_add_runtime(TCCState *s1)
{
pe_add_runtime_ex(s1, NULL);
}
PUB_FN int pe_output_file(TCCState * s1, const char *filename)
{
int ret;
struct pe_info pe;
int i;
memset(&pe, 0, sizeof pe);
pe.filename = filename;
pe.s1 = s1;
pe_add_runtime_ex(s1, &pe);
relocate_common_syms(); /* assign bss adresses */
tcc_add_linker_symbols(s1);
ret = pe_check_symbols(&pe);
if (0 == ret) {
if (PE_DLL == pe.type) {
pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
pe.imagebase = 0x10000000;
} else {
pe.imagebase = 0x00400000;
}
pe_assign_addresses(&pe);
relocate_syms(s1, 0);
for (i = 1; i < s1->nb_sections; ++i) {
Section *s = s1->sections[i];
if (s->reloc) {
relocate_section(s1, s);
pe_relocate_rva(&pe, s);
}
}
if (s1->nb_errors)
ret = 1;
else
ret = pe_write(&pe);
tcc_free(pe.sec_info);
}
#ifdef PE_PRINT_SECTIONS
pe_print_sections(s1, "tcc.log");
#endif
return ret;
}
/* ------------------------------------------------------------- */
#endif /* def TCC_TARGET_PE */
/* ------------------------------------------------------------- */
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/tccpe.c | C | lgpl | 47,290 |
#! /usr/bin/perl -w
# Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
# This file is part of GNU CC.
# GNU CC 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, or (at your option)
# any later version.
# GNU CC 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 GNU CC; see the file COPYING. If not, write to
# the Free Software Foundation, 59 Temple Place - Suite 330,
# Boston MA 02111-1307, USA.
# This does trivial (and I mean _trivial_) conversion of Texinfo
# markup to Perl POD format. It's intended to be used to extract
# something suitable for a manpage from a Texinfo document.
$output = 0;
$skipping = 0;
%sects = ();
$section = "";
@icstack = ();
@endwstack = ();
@skstack = ();
@instack = ();
$shift = "";
%defs = ();
$fnno = 1;
$inf = "";
$ibase = "";
while ($_ = shift) {
if (/^-D(.*)$/) {
if ($1 ne "") {
$flag = $1;
} else {
$flag = shift;
}
$value = "";
($flag, $value) = ($flag =~ /^([^=]+)(?:=(.+))?/);
die "no flag specified for -D\n"
unless $flag ne "";
die "flags may only contain letters, digits, hyphens, dashes and underscores\n"
unless $flag =~ /^[a-zA-Z0-9_-]+$/;
$defs{$flag} = $value;
} elsif (/^-/) {
usage();
} else {
$in = $_, next unless defined $in;
$out = $_, next unless defined $out;
usage();
}
}
if (defined $in) {
$inf = gensym();
open($inf, "<$in") or die "opening \"$in\": $!\n";
$ibase = $1 if $in =~ m|^(.+)/[^/]+$|;
} else {
$inf = \*STDIN;
}
if (defined $out) {
open(STDOUT, ">$out") or die "opening \"$out\": $!\n";
}
while(defined $inf) {
while(<$inf>) {
# Certain commands are discarded without further processing.
/^\@(?:
[a-z]+index # @*index: useful only in complete manual
|need # @need: useful only in printed manual
|(?:end\s+)?group # @group .. @end group: ditto
|page # @page: ditto
|node # @node: useful only in .info file
|(?:end\s+)?ifnottex # @ifnottex .. @end ifnottex: use contents
)\b/x and next;
chomp;
# Look for filename and title markers.
/^\@setfilename\s+([^.]+)/ and $fn = $1, next;
/^\@settitle\s+([^.]+)/ and $tl = postprocess($1), next;
# Identify a man title but keep only the one we are interested in.
/^\@c\s+man\s+title\s+([A-Za-z0-9-]+)\s+(.+)/ and do {
if (exists $defs{$1}) {
$fn = $1;
$tl = postprocess($2);
}
next;
};
# Look for blocks surrounded by @c man begin SECTION ... @c man end.
# This really oughta be @ifman ... @end ifman and the like, but such
# would require rev'ing all other Texinfo translators.
/^\@c\s+man\s+begin\s+([A-Z]+)\s+([A-Za-z0-9-]+)/ and do {
$output = 1 if exists $defs{$2};
$sect = $1;
next;
};
/^\@c\s+man\s+begin\s+([A-Z]+)/ and $sect = $1, $output = 1, next;
/^\@c\s+man\s+end/ and do {
$sects{$sect} = "" unless exists $sects{$sect};
$sects{$sect} .= postprocess($section);
$section = "";
$output = 0;
next;
};
# handle variables
/^\@set\s+([a-zA-Z0-9_-]+)\s*(.*)$/ and do {
$defs{$1} = $2;
next;
};
/^\@clear\s+([a-zA-Z0-9_-]+)/ and do {
delete $defs{$1};
next;
};
next unless $output;
# Discard comments. (Can't do it above, because then we'd never see
# @c man lines.)
/^\@c\b/ and next;
# End-block handler goes up here because it needs to operate even
# if we are skipping.
/^\@end\s+([a-z]+)/ and do {
# Ignore @end foo, where foo is not an operation which may
# cause us to skip, if we are presently skipping.
my $ended = $1;
next if $skipping && $ended !~ /^(?:ifset|ifclear|ignore|menu|iftex)$/;
die "\@end $ended without \@$ended at line $.\n" unless defined $endw;
die "\@$endw ended by \@end $ended at line $.\n" unless $ended eq $endw;
$endw = pop @endwstack;
if ($ended =~ /^(?:ifset|ifclear|ignore|menu|iftex)$/) {
$skipping = pop @skstack;
next;
} elsif ($ended =~ /^(?:example|smallexample|display)$/) {
$shift = "";
$_ = ""; # need a paragraph break
} elsif ($ended =~ /^(?:itemize|enumerate|[fv]?table)$/) {
$_ = "\n=back\n";
$ic = pop @icstack;
} else {
die "unknown command \@end $ended at line $.\n";
}
};
# We must handle commands which can cause skipping even while we
# are skipping, otherwise we will not process nested conditionals
# correctly.
/^\@ifset\s+([a-zA-Z0-9_-]+)/ and do {
push @endwstack, $endw;
push @skstack, $skipping;
$endw = "ifset";
$skipping = 1 unless exists $defs{$1};
next;
};
/^\@ifclear\s+([a-zA-Z0-9_-]+)/ and do {
push @endwstack, $endw;
push @skstack, $skipping;
$endw = "ifclear";
$skipping = 1 if exists $defs{$1};
next;
};
/^\@(ignore|menu|iftex)\b/ and do {
push @endwstack, $endw;
push @skstack, $skipping;
$endw = $1;
$skipping = 1;
next;
};
next if $skipping;
# Character entities. First the ones that can be replaced by raw text
# or discarded outright:
s/\@copyright\{\}/(c)/g;
s/\@dots\{\}/.../g;
s/\@enddots\{\}/..../g;
s/\@([.!? ])/$1/g;
s/\@[:-]//g;
s/\@bullet(?:\{\})?/*/g;
s/\@TeX\{\}/TeX/g;
s/\@pounds\{\}/\#/g;
s/\@minus(?:\{\})?/-/g;
s/\\,/,/g;
# Now the ones that have to be replaced by special escapes
# (which will be turned back into text by unmunge())
s/&/&/g;
s/\@\{/{/g;
s/\@\}/}/g;
s/\@\@/&at;/g;
# Inside a verbatim block, handle @var specially.
if ($shift ne "") {
s/\@var\{([^\}]*)\}/<$1>/g;
}
# POD doesn't interpret E<> inside a verbatim block.
if ($shift eq "") {
s/</</g;
s/>/>/g;
} else {
s/</</g;
s/>/>/g;
}
# Single line command handlers.
/^\@include\s+(.+)$/ and do {
push @instack, $inf;
$inf = gensym();
# Try cwd and $ibase.
open($inf, "<" . $1)
or open($inf, "<" . $ibase . "/" . $1)
or die "cannot open $1 or $ibase/$1: $!\n";
next;
};
/^\@(?:section|unnumbered|unnumberedsec|center)\s+(.+)$/
and $_ = "\n=head2 $1\n";
/^\@subsection\s+(.+)$/
and $_ = "\n=head3 $1\n";
# Block command handlers:
/^\@itemize\s+(\@[a-z]+|\*|-)/ and do {
push @endwstack, $endw;
push @icstack, $ic;
$ic = $1;
$_ = "\n=over 4\n";
$endw = "itemize";
};
/^\@enumerate(?:\s+([a-zA-Z0-9]+))?/ and do {
push @endwstack, $endw;
push @icstack, $ic;
if (defined $1) {
$ic = $1 . ".";
} else {
$ic = "1.";
}
$_ = "\n=over 4\n";
$endw = "enumerate";
};
/^\@([fv]?table)\s+(\@[a-z]+)/ and do {
push @endwstack, $endw;
push @icstack, $ic;
$endw = $1;
$ic = $2;
$ic =~ s/\@(?:samp|strong|key|gcctabopt|option|env)/B/;
$ic =~ s/\@(?:code|kbd)/C/;
$ic =~ s/\@(?:dfn|var|emph|cite|i)/I/;
$ic =~ s/\@(?:file)/F/;
$_ = "\n=over 4\n";
};
/^\@((?:small)?example|display)/ and do {
push @endwstack, $endw;
$endw = $1;
$shift = "\t";
$_ = ""; # need a paragraph break
};
/^\@itemx?\s*(.+)?$/ and do {
if (defined $1) {
# Entity escapes prevent munging by the <> processing below.
$_ = "\n=item $ic\<$1\>\n";
} else {
$_ = "\n=item $ic\n";
$ic =~ y/A-Ya-y/B-Zb-z/;
$ic =~ s/(\d+)/$1 + 1/eg;
}
};
$section .= $shift.$_."\n";
}
# End of current file.
close($inf);
$inf = pop @instack;
}
die "No filename or title\n" unless defined $fn && defined $tl;
$sects{NAME} = "$fn \- $tl\n";
$sects{FOOTNOTES} .= "=back\n" if exists $sects{FOOTNOTES};
for $sect (qw(NAME SYNOPSIS DESCRIPTION OPTIONS ENVIRONMENT FILES
BUGS NOTES FOOTNOTES SEEALSO AUTHOR COPYRIGHT)) {
if(exists $sects{$sect}) {
$head = $sect;
$head =~ s/SEEALSO/SEE ALSO/;
print "=head1 $head\n\n";
print scalar unmunge ($sects{$sect});
print "\n";
}
}
sub usage
{
die "usage: $0 [-D toggle...] [infile [outfile]]\n";
}
sub postprocess
{
local $_ = $_[0];
# @value{foo} is replaced by whatever 'foo' is defined as.
while (m/(\@value\{([a-zA-Z0-9_-]+)\})/g) {
if (! exists $defs{$2}) {
print STDERR "Option $2 not defined\n";
s/\Q$1\E//;
} else {
$value = $defs{$2};
s/\Q$1\E/$value/;
}
}
# Formatting commands.
# Temporary escape for @r.
s/\@r\{([^\}]*)\}/R<$1>/g;
s/\@(?:dfn|var|emph|cite|i)\{([^\}]*)\}/I<$1>/g;
s/\@(?:code|kbd)\{([^\}]*)\}/C<$1>/g;
s/\@(?:gccoptlist|samp|strong|key|option|env|command|b)\{([^\}]*)\}/B<$1>/g;
s/\@sc\{([^\}]*)\}/\U$1/g;
s/\@file\{([^\}]*)\}/F<$1>/g;
s/\@w\{([^\}]*)\}/S<$1>/g;
s/\@(?:dmn|math)\{([^\}]*)\}/$1/g;
# Cross references are thrown away, as are @noindent and @refill.
# (@noindent is impossible in .pod, and @refill is unnecessary.)
# @* is also impossible in .pod; we discard it and any newline that
# follows it. Similarly, our macro @gol must be discarded.
s/\(?\@xref\{(?:[^\}]*)\}(?:[^.<]|(?:<[^<>]*>))*\.\)?//g;
s/\s+\(\@pxref\{(?:[^\}]*)\}\)//g;
s/;\s+\@pxref\{(?:[^\}]*)\}//g;
s/\@noindent\s*//g;
s/\@refill//g;
s/\@gol//g;
s/\@\*\s*\n?//g;
# @uref can take one, two, or three arguments, with different
# semantics each time. @url and @email are just like @uref with
# one argument, for our purposes.
s/\@(?:uref|url|email)\{([^\},]*)\}/<B<$1>>/g;
s/\@uref\{([^\},]*),([^\},]*)\}/$2 (C<$1>)/g;
s/\@uref\{([^\},]*),([^\},]*),([^\},]*)\}/$3/g;
# Turn B<blah I<blah> blah> into B<blah> I<blah> B<blah> to
# match Texinfo semantics of @emph inside @samp. Also handle @r
# inside bold.
s/</</g;
s/>/>/g;
1 while s/B<((?:[^<>]|I<[^<>]*>)*)R<([^>]*)>/B<$1>${2}B</g;
1 while (s/B<([^<>]*)I<([^>]+)>/B<$1>I<$2>B</g);
1 while (s/I<([^<>]*)B<([^>]+)>/I<$1>B<$2>I</g);
s/[BI]<>//g;
s/([BI])<(\s+)([^>]+)>/$2$1<$3>/g;
s/([BI])<([^>]+?)(\s+)>/$1<$2>$3/g;
# Extract footnotes. This has to be done after all other
# processing because otherwise the regexp will choke on formatting
# inside @footnote.
while (/\@footnote/g) {
s/\@footnote\{([^\}]+)\}/[$fnno]/;
add_footnote($1, $fnno);
$fnno++;
}
return $_;
}
sub unmunge
{
# Replace escaped symbols with their equivalents.
local $_ = $_[0];
s/</E<lt>/g;
s/>/E<gt>/g;
s/{/\{/g;
s/}/\}/g;
s/&at;/\@/g;
s/&/&/g;
return $_;
}
sub add_footnote
{
unless (exists $sects{FOOTNOTES}) {
$sects{FOOTNOTES} = "\n=over 4\n\n";
}
$sects{FOOTNOTES} .= "=item $fnno.\n\n"; $fnno++;
$sects{FOOTNOTES} .= $_[0];
$sects{FOOTNOTES} .= "\n\n";
}
# stolen from Symbol.pm
{
my $genseq = 0;
sub gensym
{
my $name = "GEN" . $genseq++;
my $ref = \*{$name};
delete $::{$name};
return $ref;
}
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/.svn/text-base/texi2pod.pl.svn-base | Perl | lgpl | 11,030 |
#!/bin/sh
#
# tcc configure script (c) 2003 Fabrice Bellard
#
# set temporary file name
if test ! -z "$TMPDIR" ; then
TMPDIR1="${TMPDIR}"
elif test ! -z "$TEMPDIR" ; then
TMPDIR1="${TEMPDIR}"
else
TMPDIR1="/tmp"
fi
TMPC="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.c"
TMPO="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.o"
TMPE="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}"
TMPS="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.S"
TMPH="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.h"
# default parameters
build_cross="no"
use_libgcc="no"
prefix=""
execprefix=""
bindir=""
libdir=""
tccdir=""
includedir=""
mandir=""
sysroot=""
cross_prefix=""
cc="gcc"
host_cc="gcc"
ar="ar"
strip="strip"
cpu=`uname -m`
case "$cpu" in
i386|i486|i586|i686|i86pc|BePC)
cpu="x86"
;;
x86_64)
cpu="x86-64"
;;
armv4l)
cpu="armv4l"
;;
alpha)
cpu="alpha"
;;
"Power Macintosh"|ppc|ppc64)
cpu="powerpc"
;;
mips)
cpu="mips"
;;
s390)
cpu="s390"
;;
*)
cpu="unknown"
;;
esac
gprof="no"
bigendian="no"
mingw32="no"
LIBSUF=".a"
EXESUF=""
# OS specific
targetos=`uname -s`
case $targetos in
MINGW32*)
mingw32="yes"
;;
DragonFly)
noldl="yes"
;;
OpenBSD)
noldl="yes"
;;
*) ;;
esac
# find source path
# XXX: we assume an absolute path is given when launching configure,
# except in './configure' case.
source_path=${0%configure}
source_path=${source_path%/}
source_path_used="yes"
if test -z "$source_path" -o "$source_path" = "." ; then
source_path=`pwd`
source_path_used="no"
fi
for opt do
case "$opt" in
--prefix=*) prefix=`echo $opt | cut -d '=' -f 2`
;;
--exec-prefix=*) execprefix=`echo $opt | cut -d '=' -f 2`
;;
--bindir=*) bindir=`echo $opt | cut -d '=' -f 2`
;;
--libdir=*) libdir=`echo $opt | cut -d '=' -f 2`
;;
--includedir=*) includedir=`echo $opt | cut -d '=' -f 2`
;;
--mandir=*) mandir=`echo $opt | cut -d '=' -f 2`
;;
--sysroot=*) sysroot=`echo $opt | cut -d '=' -f 2`
;;
--source-path=*) source_path=`echo $opt | cut -d '=' -f 2`
;;
--cross-prefix=*) cross_prefix=`echo $opt | cut -d '=' -f 2`
;;
--cc=*) cc=`echo $opt | cut -d '=' -f 2`
;;
--extra-cflags=*) CFLAGS="${opt#--extra-cflags=}"
;;
--extra-ldflags=*) LDFLAGS="${opt#--extra-ldflags=}"
;;
--extra-libs=*) extralibs=${opt#--extra-libs=}
;;
--cpu=*) cpu=`echo $opt | cut -d '=' -f 2`
;;
--enable-gprof) gprof="yes"
;;
--enable-mingw32) mingw32="yes" ; cross_prefix="i386-mingw32-"
;;
--enable-cross) build_cross="yes"
;;
--with-libgcc) use_libgcc="yes"
;;
esac
done
# Checking for CFLAGS
if test -z "$CFLAGS"; then
CFLAGS="-O2"
fi
cc="${cross_prefix}${cc}"
ar="${cross_prefix}${ar}"
strip="${cross_prefix}${strip}"
if test "$mingw32" = "yes" ; then
LIBSUF=".lib"
EXESUF=".exe"
fi
if test -z "$cross_prefix" ; then
# ---
# big/little endian test
cat > $TMPC << EOF
#include <inttypes.h>
int main(int argc, char ** argv){
volatile uint32_t i=0x01234567;
return (*((uint8_t*)(&i))) == 0x67;
}
EOF
if $cc -o $TMPE $TMPC 2>/dev/null ; then
$TMPE && bigendian="yes"
else
echo big/little test failed
fi
else
# if cross compiling, cannot launch a program, so make a static guess
if test "$cpu" = "powerpc" -o "$cpu" = "mips" -o "$cpu" = "s390" ; then
bigendian="yes"
fi
fi
# check gcc version
cat > $TMPC <<EOF
int main(void) {
#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)
return 0;
#else
#error gcc < 3.2
#endif
}
EOF
gcc_major="2"
if $cc -o $TMPO $TMPC 2> /dev/null ; then
gcc_major="3"
fi
cat > $TMPC <<EOF
int main(void) {
#if __GNUC__ >= 4
return 0;
#else
#error gcc < 4
#endif
}
EOF
if $cc -o $TMPO $TMPC 2> /dev/null ; then
gcc_major="4"
fi
if test x"$1" = x"-h" -o x"$1" = x"--help" ; then
cat << EOF
Usage: configure [options]
Options: [defaults in brackets after descriptions]
EOF
echo "Standard options:"
echo " --help print this message"
echo " --prefix=PREFIX install in PREFIX [$prefix]"
echo " --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX"
echo " [same as prefix]"
echo " --bindir=DIR user executables in DIR [EPREFIX/bin]"
echo " --libdir=DIR object code libraries in DIR [EPREFIX/lib]"
echo " --includedir=DIR C header files in DIR [PREFIX/include]"
echo " --mandir=DIR man documentation in DIR [PREFIX/man]"
echo " --enable-cross build cross compilers"
echo ""
echo "Advanced options (experts only):"
echo " --source-path=PATH path of source code [$source_path]"
echo " --cross-prefix=PREFIX use PREFIX for compile tools [$cross_prefix]"
echo " --sysroot=PREFIX prepend PREFIX to library/include paths []"
echo " --cc=CC use C compiler CC [$cc]"
echo " --with-libgcc use /lib/libgcc_s.so.1 instead of libtcc1.a"
echo ""
#echo "NOTE: The object files are build at the place where configure is launched"
exit 1
fi
if test "$mingw32" = "yes" ; then
if test -z "$prefix" ; then
prefix="C:/Program Files/tcc"
fi
execprefix="$prefix"
bindir="$prefix"
tccdir="$prefix"
docdir="$prefix/doc"
else
if test -z "$prefix" ; then
prefix="/usr/local"
fi
if test x"$execprefix" = x""; then
execprefix="${prefix}"
fi
if test x"$bindir" = x""; then
bindir="${execprefix}/bin"
fi
if test x"$docdir" = x""; then
docdir="$prefix/share/doc/tcc"
fi
fi # mingw32
if test x"$libdir" = x""; then
libdir="${execprefix}/lib"
fi
if test x"$tccdir" = x""; then
tccdir="${execprefix}/lib/tcc"
fi
if test x"$mandir" = x""; then
mandir="${prefix}/man"
fi
if test x"$includedir" = x""; then
includedir="${prefix}/include"
fi
echo "Binary directory $bindir"
echo "TinyCC directory $tccdir"
echo "Library directory $libdir"
echo "Include directory $includedir"
echo "Manual directory $mandir"
echo "Doc directory $docdir"
echo "Target root prefix $sysroot"
echo "Source path $source_path"
echo "C compiler $cc"
echo "CPU $cpu"
echo "Big Endian $bigendian"
echo "gprof enabled $gprof"
echo "cross compilers $build_cross"
echo "use libgcc $use_libgcc"
echo "Creating config.mak and config.h"
echo "# Automatically generated by configure - do not modify" > config.mak
echo "/* Automatically generated by configure - do not modify */" > $TMPH
echo "prefix=$prefix" >> config.mak
echo "bindir=$bindir" >> config.mak
echo "tccdir=$tccdir" >> config.mak
echo "libdir=$libdir" >> config.mak
echo "includedir=$includedir" >> config.mak
echo "mandir=$mandir" >> config.mak
echo "docdir=$docdir" >> config.mak
echo "#define CONFIG_SYSROOT \"$sysroot\"" >> $TMPH
echo "#define CONFIG_TCCDIR \"$tccdir\"" >> $TMPH
echo "CC=$cc" >> config.mak
echo "GCC_MAJOR=$gcc_major" >> config.mak
echo "#define GCC_MAJOR $gcc_major" >> $TMPH
echo "HOST_CC=$host_cc" >> config.mak
echo "AR=$ar" >> config.mak
echo "STRIP=$strip -s -R .comment -R .note" >> config.mak
echo "CFLAGS=$CFLAGS" >> config.mak
echo "LDFLAGS=$LDFLAGS" >> config.mak
echo "LIBSUF=$LIBSUF" >> config.mak
echo "EXESUF=$EXESUF" >> config.mak
if test "$cpu" = "x86" ; then
echo "ARCH=i386" >> config.mak
echo "#define HOST_I386 1" >> $TMPH
elif test "$cpu" = "x86-64" ; then
echo "ARCH=x86-64" >> config.mak
echo "#define HOST_X86_64 1" >> $TMPH
elif test "$cpu" = "armv4l" ; then
echo "ARCH=arm" >> config.mak
echo "#define HOST_ARM 1" >> $TMPH
elif test "$cpu" = "powerpc" ; then
echo "ARCH=ppc" >> config.mak
echo "#define HOST_PPC 1" >> $TMPH
elif test "$cpu" = "mips" ; then
echo "ARCH=mips" >> config.mak
echo "#define HOST_MIPS 1" >> $TMPH
elif test "$cpu" = "s390" ; then
echo "ARCH=s390" >> config.mak
echo "#define HOST_S390 1" >> $TMPH
elif test "$cpu" = "alpha" ; then
echo "ARCH=alpha" >> config.mak
echo "#define HOST_ALPHA 1" >> $TMPH
else
echo "Unsupported CPU"
exit 1
fi
if test "$noldl" = "yes" ; then
echo "CONFIG_NOLDL=yes" >> config.mak
fi
if test "$mingw32" = "yes" ; then
echo "CONFIG_WIN32=yes" >> config.mak
echo "#define CONFIG_WIN32 1" >> $TMPH
fi
if test "$bigendian" = "yes" ; then
echo "WORDS_BIGENDIAN=yes" >> config.mak
echo "#define WORDS_BIGENDIAN 1" >> $TMPH
fi
if test "$gprof" = "yes" ; then
echo "TARGET_GPROF=yes" >> config.mak
echo "#define HAVE_GPROF 1" >> $TMPH
fi
if test "$build_cross" = "yes" ; then
echo "CONFIG_CROSS=yes" >> config.mak
fi
if test "$use_libgcc" = "yes" ; then
echo "#define CONFIG_USE_LIBGCC" >> $TMPH
echo "CONFIG_USE_LIBGCC=yes" >> config.mak
fi
version=`head $source_path/VERSION`
echo "VERSION=$version" >>config.mak
echo "#define TCC_VERSION \"$version\"" >> $TMPH
echo "@set VERSION $version" > config.texi
# build tree in object directory if source path is different from current one
if test "$source_path_used" = "yes" ; then
DIRS="tests"
FILES="Makefile tests/Makefile"
for dir in $DIRS ; do
mkdir -p $dir
done
for f in $FILES ; do
ln -sf $source_path/$f $f
done
fi
echo "SRC_PATH=$source_path" >> config.mak
diff $TMPH config.h >/dev/null 2>&1
if test $? -ne 0 ; then
mv -f $TMPH config.h
else
echo "config.h is unchanged"
fi
rm -f $TMPO $TMPC $TMPE $TMPS $TMPH
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/.svn/text-base/configure.svn-base | Shell | lgpl | 9,276 |
/*
* X86 code generator for TCC
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* number of available registers */
#define NB_REGS 4
/* a register can belong to several classes. The classes must be
sorted from more general to more precise (see gv2() code which does
assumptions on it). */
#define RC_INT 0x0001 /* generic integer register */
#define RC_FLOAT 0x0002 /* generic float register */
#define RC_EAX 0x0004
#define RC_ST0 0x0008
#define RC_ECX 0x0010
#define RC_EDX 0x0020
#define RC_IRET RC_EAX /* function return: integer register */
#define RC_LRET RC_EDX /* function return: second integer register */
#define RC_FRET RC_ST0 /* function return: float register */
/* pretty names for the registers */
enum {
TREG_EAX = 0,
TREG_ECX,
TREG_EDX,
TREG_ST0,
};
int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_EAX,
/* ecx */ RC_INT | RC_ECX,
/* edx */ RC_INT | RC_EDX,
/* st0 */ RC_FLOAT | RC_ST0,
};
/* return registers for function */
#define REG_IRET TREG_EAX /* single word int return register */
#define REG_LRET TREG_EDX /* second word return register (for long long) */
#define REG_FRET TREG_ST0 /* float return register */
/* defined if function parameters must be evaluated in reverse order */
#define INVERT_FUNC_PARAMS
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* pointer size, in bytes */
#define PTR_SIZE 4
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 12
#define LDOUBLE_ALIGN 4
/* maximum alignment (for aligned attribute support) */
#define MAX_ALIGN 8
/******************************************************/
/* ELF defines */
#define EM_TCC_TARGET EM_386
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_386_32
#define R_JMP_SLOT R_386_JMP_SLOT
#define R_COPY R_386_COPY
#define ELF_START_ADDR 0x08048000
#define ELF_PAGE_SIZE 0x1000
/******************************************************/
static unsigned long func_sub_sp_offset;
static unsigned long func_bound_offset;
static int func_ret_sub;
/* XXX: make it faster ? */
void g(int c)
{
int ind1;
ind1 = ind + 1;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
cur_text_section->data[ind] = c;
ind = ind1;
}
void o(unsigned int c)
{
while (c) {
g(c);
c = c >> 8;
}
}
void gen_le32(int c)
{
g(c);
g(c >> 8);
g(c >> 16);
g(c >> 24);
}
/* output a symbol and patch all calls to it */
void gsym_addr(int t, int a)
{
int n, *ptr;
while (t) {
ptr = (int *)(cur_text_section->data + t);
n = *ptr; /* next value */
*ptr = a - t - 4;
t = n;
}
}
void gsym(int t)
{
gsym_addr(t, ind);
}
/* psym is used to put an instruction with a data field which is a
reference to a symbol. It is in fact the same as oad ! */
#define psym oad
/* instruction + 4 bytes data. Return the address of the data */
static int oad(int c, int s)
{
int ind1;
o(c);
ind1 = ind + 4;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
*(int *)(cur_text_section->data + ind) = s;
s = ind;
ind = ind1;
return s;
}
/* output constant with relocation if 'r & VT_SYM' is true */
static void gen_addr32(int r, Sym *sym, int c)
{
if (r & VT_SYM)
greloc(cur_text_section, sym, ind, R_386_32);
gen_le32(c);
}
/* generate a modrm reference. 'op_reg' contains the addtionnal 3
opcode bits */
static void gen_modrm(int op_reg, int r, Sym *sym, int c)
{
op_reg = op_reg << 3;
if ((r & VT_VALMASK) == VT_CONST) {
/* constant memory reference */
o(0x05 | op_reg);
gen_addr32(r, sym, c);
} else if ((r & VT_VALMASK) == VT_LOCAL) {
/* currently, we use only ebp as base */
if (c == (char)c) {
/* short reference */
o(0x45 | op_reg);
g(c);
} else {
oad(0x85 | op_reg, c);
}
} else {
g(0x00 | op_reg | (r & VT_VALMASK));
}
}
/* load 'r' from value 'sv' */
void load(int r, SValue *sv)
{
int v, t, ft, fc, fr;
SValue v1;
fr = sv->r;
ft = sv->type.t;
fc = sv->c.ul;
v = fr & VT_VALMASK;
if (fr & VT_LVAL) {
if (v == VT_LLOCAL) {
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fr = r;
}
if ((ft & VT_BTYPE) == VT_FLOAT) {
o(0xd9); /* flds */
r = 0;
} else if ((ft & VT_BTYPE) == VT_DOUBLE) {
o(0xdd); /* fldl */
r = 0;
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xdb); /* fldt */
r = 5;
} else if ((ft & VT_TYPE) == VT_BYTE) {
o(0xbe0f); /* movsbl */
} else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED)) {
o(0xb60f); /* movzbl */
} else if ((ft & VT_TYPE) == VT_SHORT) {
o(0xbf0f); /* movswl */
} else if ((ft & VT_TYPE) == (VT_SHORT | VT_UNSIGNED)) {
o(0xb70f); /* movzwl */
} else {
o(0x8b); /* movl */
}
gen_modrm(r, fr, sv->sym, fc);
} else {
if (v == VT_CONST) {
o(0xb8 + r); /* mov $xx, r */
gen_addr32(fr, sv->sym, fc);
} else if (v == VT_LOCAL) {
o(0x8d); /* lea xxx(%ebp), r */
gen_modrm(r, VT_LOCAL, sv->sym, fc);
} else if (v == VT_CMP) {
oad(0xb8 + r, 0); /* mov $0, r */
o(0x0f); /* setxx %br */
o(fc);
o(0xc0 + r);
} else if (v == VT_JMP || v == VT_JMPI) {
t = v & 1;
oad(0xb8 + r, t); /* mov $1, r */
o(0x05eb); /* jmp after */
gsym(fc);
oad(0xb8 + r, t ^ 1); /* mov $0, r */
} else if (v != r) {
o(0x89);
o(0xc0 + r + v * 8); /* mov v, r */
}
}
}
/* store register 'r' in lvalue 'v' */
void store(int r, SValue *v)
{
int fr, bt, ft, fc;
ft = v->type.t;
fc = v->c.ul;
fr = v->r & VT_VALMASK;
bt = ft & VT_BTYPE;
/* XXX: incorrect if float reg to reg */
if (bt == VT_FLOAT) {
o(0xd9); /* fsts */
r = 2;
} else if (bt == VT_DOUBLE) {
o(0xdd); /* fstpl */
r = 2;
} else if (bt == VT_LDOUBLE) {
o(0xc0d9); /* fld %st(0) */
o(0xdb); /* fstpt */
r = 7;
} else {
if (bt == VT_SHORT)
o(0x66);
if (bt == VT_BYTE || bt == VT_BOOL)
o(0x88);
else
o(0x89);
}
if (fr == VT_CONST ||
fr == VT_LOCAL ||
(v->r & VT_LVAL)) {
gen_modrm(r, v->r, v->sym, fc);
} else if (fr != r) {
o(0xc0 + fr + r * 8); /* mov r, fr */
}
}
static void gadd_sp(int val)
{
if (val == (char)val) {
o(0xc483);
g(val);
} else {
oad(0xc481, val); /* add $xxx, %esp */
}
}
/* 'is_jmp' is '1' if it is a jump */
static void gcall_or_jmp(int is_jmp)
{
int r;
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* constant case */
if (vtop->r & VT_SYM) {
/* relocation case */
greloc(cur_text_section, vtop->sym,
ind + 1, R_386_PC32);
} else {
/* put an empty PC32 relocation */
put_elf_reloc(symtab_section, cur_text_section,
ind + 1, R_386_PC32, 0);
}
oad(0xe8 + is_jmp, vtop->c.ul - 4); /* call/jmp im */
} else {
/* otherwise, indirect call */
r = gv(RC_INT);
o(0xff); /* call/jmp *r */
o(0xd0 + r + (is_jmp << 4));
}
}
static uint8_t fastcall_regs[3] = { TREG_EAX, TREG_EDX, TREG_ECX };
static uint8_t fastcallw_regs[2] = { TREG_ECX, TREG_EDX };
/* Generate function call. The function address is pushed first, then
all the parameters in call order. This functions pops all the
parameters and the function address. */
void gfunc_call(int nb_args)
{
int size, align, r, args_size, i, func_call;
Sym *func_sym;
args_size = 0;
for(i = 0;i < nb_args; i++) {
if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
size = type_size(&vtop->type, &align);
/* align to stack align size */
size = (size + 3) & ~3;
/* allocate the necessary size on stack */
oad(0xec81, size); /* sub $xxx, %esp */
/* generate structure store */
r = get_reg(RC_INT);
o(0x89); /* mov %esp, r */
o(0xe0 + r);
vset(&vtop->type, r | VT_LVAL, 0);
vswap();
vstore();
args_size += size;
} else if (is_float(vtop->type.t)) {
gv(RC_FLOAT); /* only one float register */
if ((vtop->type.t & VT_BTYPE) == VT_FLOAT)
size = 4;
else if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
size = 8;
else
size = 12;
oad(0xec81, size); /* sub $xxx, %esp */
if (size == 12)
o(0x7cdb);
else
o(0x5cd9 + size - 4); /* fstp[s|l] 0(%esp) */
g(0x24);
g(0x00);
args_size += size;
} else {
/* simple type (currently always same size) */
/* XXX: implicit cast ? */
r = gv(RC_INT);
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
size = 8;
o(0x50 + vtop->r2); /* push r */
} else {
size = 4;
}
o(0x50 + r); /* push r */
args_size += size;
}
vtop--;
}
save_regs(0); /* save used temporary registers */
func_sym = vtop->type.ref;
func_call = FUNC_CALL(func_sym->r);
/* fast call case */
if ((func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) ||
func_call == FUNC_FASTCALLW) {
int fastcall_nb_regs;
uint8_t *fastcall_regs_ptr;
if (func_call == FUNC_FASTCALLW) {
fastcall_regs_ptr = fastcallw_regs;
fastcall_nb_regs = 2;
} else {
fastcall_regs_ptr = fastcall_regs;
fastcall_nb_regs = func_call - FUNC_FASTCALL1 + 1;
}
for(i = 0;i < fastcall_nb_regs; i++) {
if (args_size <= 0)
break;
o(0x58 + fastcall_regs_ptr[i]); /* pop r */
/* XXX: incorrect for struct/floats */
args_size -= 4;
}
}
gcall_or_jmp(0);
if (args_size && func_call != FUNC_STDCALL)
gadd_sp(args_size);
vtop--;
}
#ifdef TCC_TARGET_PE
#define FUNC_PROLOG_SIZE 10
#else
#define FUNC_PROLOG_SIZE 9
#endif
/* generate function prolog of type 't' */
void gfunc_prolog(CType *func_type)
{
int addr, align, size, func_call, fastcall_nb_regs;
int param_index, param_addr;
uint8_t *fastcall_regs_ptr;
Sym *sym;
CType *type;
sym = func_type->ref;
func_call = FUNC_CALL(sym->r);
addr = 8;
loc = 0;
if (func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) {
fastcall_nb_regs = func_call - FUNC_FASTCALL1 + 1;
fastcall_regs_ptr = fastcall_regs;
} else if (func_call == FUNC_FASTCALLW) {
fastcall_nb_regs = 2;
fastcall_regs_ptr = fastcallw_regs;
} else {
fastcall_nb_regs = 0;
fastcall_regs_ptr = NULL;
}
param_index = 0;
ind += FUNC_PROLOG_SIZE;
func_sub_sp_offset = ind;
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->type;
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
/* XXX: fastcall case ? */
func_vc = addr;
addr += 4;
param_index++;
}
/* define parameters */
while ((sym = sym->next) != NULL) {
type = &sym->type;
size = type_size(type, &align);
size = (size + 3) & ~3;
#ifdef FUNC_STRUCT_PARAM_AS_PTR
/* structs are passed as pointer */
if ((type->t & VT_BTYPE) == VT_STRUCT) {
size = 4;
}
#endif
if (param_index < fastcall_nb_regs) {
/* save FASTCALL register */
loc -= 4;
o(0x89); /* movl */
gen_modrm(fastcall_regs_ptr[param_index], VT_LOCAL, NULL, loc);
param_addr = loc;
} else {
param_addr = addr;
addr += size;
}
sym_push(sym->v & ~SYM_FIELD, type,
VT_LOCAL | lvalue_type(type->t), param_addr);
param_index++;
}
func_ret_sub = 0;
/* pascal type call ? */
if (func_call == FUNC_STDCALL)
func_ret_sub = addr - 8;
/* leave some room for bound checking code */
if (tcc_state->do_bounds_check) {
oad(0xb8, 0); /* lbound section pointer */
oad(0xb8, 0); /* call to function */
func_bound_offset = lbounds_section->data_offset;
}
}
/* generate function epilog */
void gfunc_epilog(void)
{
int v, saved_ind;
#ifdef CONFIG_TCC_BCHECK
if (tcc_state->do_bounds_check
&& func_bound_offset != lbounds_section->data_offset) {
int saved_ind;
int *bounds_ptr;
Sym *sym, *sym_data;
/* add end of table info */
bounds_ptr = section_ptr_add(lbounds_section, sizeof(int));
*bounds_ptr = 0;
/* generate bound local allocation */
saved_ind = ind;
ind = func_sub_sp_offset;
sym_data = get_sym_ref(&char_pointer_type, lbounds_section,
func_bound_offset, lbounds_section->data_offset);
greloc(cur_text_section, sym_data,
ind + 1, R_386_32);
oad(0xb8, 0); /* mov %eax, xxx */
sym = external_global_sym(TOK___bound_local_new, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
ind = saved_ind;
/* generate bound check local freeing */
o(0x5250); /* save returned value, if any */
greloc(cur_text_section, sym_data,
ind + 1, R_386_32);
oad(0xb8, 0); /* mov %eax, xxx */
sym = external_global_sym(TOK___bound_local_delete, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
o(0x585a); /* restore returned value, if any */
}
#endif
o(0xc9); /* leave */
if (func_ret_sub == 0) {
o(0xc3); /* ret */
} else {
o(0xc2); /* ret n */
g(func_ret_sub);
g(func_ret_sub >> 8);
}
/* align local size to word & save local variables */
v = (-loc + 3) & -4;
saved_ind = ind;
ind = func_sub_sp_offset - FUNC_PROLOG_SIZE;
#ifdef TCC_TARGET_PE
if (v >= 4096) {
Sym *sym = external_global_sym(TOK___chkstk, &func_old_type, 0);
oad(0xb8, v); /* mov stacksize, %eax */
oad(0xe8, -4); /* call __chkstk, (does the stackframe too) */
greloc(cur_text_section, sym, ind-4, R_386_PC32);
} else
#endif
{
o(0xe58955); /* push %ebp, mov %esp, %ebp */
o(0xec81); /* sub esp, stacksize */
gen_le32(v);
#if FUNC_PROLOG_SIZE == 10
o(0x90); /* adjust to FUNC_PROLOG_SIZE */
#endif
}
ind = saved_ind;
}
/* generate a jump to a label */
int gjmp(int t)
{
return psym(0xe9, t);
}
/* generate a jump to a fixed address */
void gjmp_addr(int a)
{
int r;
r = a - ind - 2;
if (r == (char)r) {
g(0xeb);
g(r);
} else {
oad(0xe9, a - ind - 5);
}
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
int gtst(int inv, int t)
{
int v, *p;
v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
/* fast case : can jump directly since flags are set */
g(0x0f);
t = psym((vtop->c.i - 16) ^ inv, t);
} else if (v == VT_JMP || v == VT_JMPI) {
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
while (*p != 0)
p = (int *)(cur_text_section->data + *p);
*p = t;
t = vtop->c.i;
} else {
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->type.t) ||
(vtop->type.t & VT_BTYPE) == VT_LLONG) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
v = gv(RC_INT);
o(0x85);
o(0xc0 + v * 9);
g(0x0f);
t = psym(0x85 ^ inv, t);
}
}
vtop--;
return t;
}
/* generate an integer binary operation */
void gen_opi(int op)
{
int r, fr, opc, c;
switch(op) {
case '+':
case TOK_ADDC1: /* add with carry generation */
opc = 0;
gen_op8:
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant case */
vswap();
r = gv(RC_INT);
vswap();
c = vtop->c.i;
if (c == (char)c) {
/* XXX: generate inc and dec for smaller code ? */
o(0x83);
o(0xc0 | (opc << 3) | r);
g(c);
} else {
o(0x81);
oad(0xc0 | (opc << 3) | r, c);
}
} else {
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
o((opc << 3) | 0x01);
o(0xc0 + r + fr * 8);
}
vtop--;
if (op >= TOK_ULT && op <= TOK_GT) {
vtop->r = VT_CMP;
vtop->c.i = op;
}
break;
case '-':
case TOK_SUBC1: /* sub with carry generation */
opc = 5;
goto gen_op8;
case TOK_ADDC2: /* add with carry use */
opc = 2;
goto gen_op8;
case TOK_SUBC2: /* sub with carry use */
opc = 3;
goto gen_op8;
case '&':
opc = 4;
goto gen_op8;
case '^':
opc = 6;
goto gen_op8;
case '|':
opc = 1;
goto gen_op8;
case '*':
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
o(0xaf0f); /* imul fr, r */
o(0xc0 + fr + r * 8);
break;
case TOK_SHL:
opc = 4;
goto gen_shift;
case TOK_SHR:
opc = 5;
goto gen_shift;
case TOK_SAR:
opc = 7;
gen_shift:
opc = 0xc0 | (opc << 3);
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant case */
vswap();
r = gv(RC_INT);
vswap();
c = vtop->c.i & 0x1f;
o(0xc1); /* shl/shr/sar $xxx, r */
o(opc | r);
g(c);
} else {
/* we generate the shift in ecx */
gv2(RC_INT, RC_ECX);
r = vtop[-1].r;
o(0xd3); /* shl/shr/sar %cl, r */
o(opc | r);
}
vtop--;
break;
case '/':
case TOK_UDIV:
case TOK_PDIV:
case '%':
case TOK_UMOD:
case TOK_UMULL:
/* first operand must be in eax */
/* XXX: need better constraint for second operand */
gv2(RC_EAX, RC_ECX);
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
save_reg(TREG_EDX);
if (op == TOK_UMULL) {
o(0xf7); /* mul fr */
o(0xe0 + fr);
vtop->r2 = TREG_EDX;
r = TREG_EAX;
} else {
if (op == TOK_UDIV || op == TOK_UMOD) {
o(0xf7d231); /* xor %edx, %edx, div fr, %eax */
o(0xf0 + fr);
} else {
o(0xf799); /* cltd, idiv fr, %eax */
o(0xf8 + fr);
}
if (op == '%' || op == TOK_UMOD)
r = TREG_EDX;
else
r = TREG_EAX;
}
vtop->r = r;
break;
default:
opc = 7;
goto gen_op8;
}
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
/* XXX: need to use ST1 too */
void gen_opf(int op)
{
int a, ft, fc, swapped, r;
/* convert constants to memory references */
if ((vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
vswap();
gv(RC_FLOAT);
vswap();
}
if ((vtop[0].r & (VT_VALMASK | VT_LVAL)) == VT_CONST)
gv(RC_FLOAT);
/* must put at least one value in the floating point register */
if ((vtop[-1].r & VT_LVAL) &&
(vtop[0].r & VT_LVAL)) {
vswap();
gv(RC_FLOAT);
vswap();
}
swapped = 0;
/* swap the stack if needed so that t1 is the register and t2 is
the memory reference */
if (vtop[-1].r & VT_LVAL) {
vswap();
swapped = 1;
}
if (op >= TOK_ULT && op <= TOK_GT) {
/* load on stack second operand */
load(TREG_ST0, vtop);
save_reg(TREG_EAX); /* eax is used by FP comparison code */
if (op == TOK_GE || op == TOK_GT)
swapped = !swapped;
else if (op == TOK_EQ || op == TOK_NE)
swapped = 0;
if (swapped)
o(0xc9d9); /* fxch %st(1) */
o(0xe9da); /* fucompp */
o(0xe0df); /* fnstsw %ax */
if (op == TOK_EQ) {
o(0x45e480); /* and $0x45, %ah */
o(0x40fC80); /* cmp $0x40, %ah */
} else if (op == TOK_NE) {
o(0x45e480); /* and $0x45, %ah */
o(0x40f480); /* xor $0x40, %ah */
op = TOK_NE;
} else if (op == TOK_GE || op == TOK_LE) {
o(0x05c4f6); /* test $0x05, %ah */
op = TOK_EQ;
} else {
o(0x45c4f6); /* test $0x45, %ah */
op = TOK_EQ;
}
vtop--;
vtop->r = VT_CMP;
vtop->c.i = op;
} else {
/* no memory reference possible for long double operations */
if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
load(TREG_ST0, vtop);
swapped = !swapped;
}
switch(op) {
default:
case '+':
a = 0;
break;
case '-':
a = 4;
if (swapped)
a++;
break;
case '*':
a = 1;
break;
case '/':
a = 6;
if (swapped)
a++;
break;
}
ft = vtop->type.t;
fc = vtop->c.ul;
if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xde); /* fxxxp %st, %st(1) */
o(0xc1 + (a << 3));
} else {
/* if saved lvalue, then we must reload it */
r = vtop->r;
if ((r & VT_VALMASK) == VT_LLOCAL) {
SValue v1;
r = get_reg(RC_INT);
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fc = 0;
}
if ((ft & VT_BTYPE) == VT_DOUBLE)
o(0xdc);
else
o(0xd8);
gen_modrm(a, r, vtop->sym, fc);
}
vtop--;
}
}
/* convert integers to fp 't' type. Must handle 'int', 'unsigned int'
and 'long long' cases. */
void gen_cvt_itof(int t)
{
save_reg(TREG_ST0);
gv(RC_INT);
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
/* signed long long to float/double/long double (unsigned case
is handled generically) */
o(0x50 + vtop->r2); /* push r2 */
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x242cdf); /* fildll (%esp) */
o(0x08c483); /* add $8, %esp */
} else if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
(VT_INT | VT_UNSIGNED)) {
/* unsigned int to float/double/long double */
o(0x6a); /* push $0 */
g(0x00);
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x242cdf); /* fildll (%esp) */
o(0x08c483); /* add $8, %esp */
} else {
/* int to float/double/long double */
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x2404db); /* fildl (%esp) */
o(0x04c483); /* add $4, %esp */
}
vtop->r = TREG_ST0;
}
/* convert fp to int 't' type */
/* XXX: handle long long case */
void gen_cvt_ftoi(int t)
{
int r, r2, size;
Sym *sym;
CType ushort_type;
ushort_type.t = VT_SHORT | VT_UNSIGNED;
gv(RC_FLOAT);
if (t != VT_INT)
size = 8;
else
size = 4;
o(0x2dd9); /* ldcw xxx */
sym = external_global_sym(TOK___tcc_int_fpu_control,
&ushort_type, VT_LVAL);
greloc(cur_text_section, sym,
ind, R_386_32);
gen_le32(0);
oad(0xec81, size); /* sub $xxx, %esp */
if (size == 4)
o(0x1cdb); /* fistpl */
else
o(0x3cdf); /* fistpll */
o(0x24);
o(0x2dd9); /* ldcw xxx */
sym = external_global_sym(TOK___tcc_fpu_control,
&ushort_type, VT_LVAL);
greloc(cur_text_section, sym,
ind, R_386_32);
gen_le32(0);
r = get_reg(RC_INT);
o(0x58 + r); /* pop r */
if (size == 8) {
if (t == VT_LLONG) {
vtop->r = r; /* mark reg as used */
r2 = get_reg(RC_INT);
o(0x58 + r2); /* pop r2 */
vtop->r2 = r2;
} else {
o(0x04c483); /* add $4, %esp */
}
}
vtop->r = r;
}
/* convert from one floating point type to another */
void gen_cvt_ftof(int t)
{
/* all we have to do on i386 is to put the float in a register */
gv(RC_FLOAT);
}
/* computed goto support */
void ggoto(void)
{
gcall_or_jmp(1);
vtop--;
}
/* bound check support functions */
#ifdef CONFIG_TCC_BCHECK
/* generate a bounded pointer addition */
void gen_bounded_ptr_add(void)
{
Sym *sym;
/* prepare fast i386 function call (args in eax and edx) */
gv2(RC_EAX, RC_EDX);
/* save all temporary registers */
vtop -= 2;
save_regs(0);
/* do a fast function call */
sym = external_global_sym(TOK___bound_ptr_add, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
/* returned pointer is in eax */
vtop++;
vtop->r = TREG_EAX | VT_BOUNDED;
/* address of bounding function call point */
vtop->c.ul = (cur_text_section->reloc->data_offset - sizeof(Elf32_Rel));
}
/* patch pointer addition in vtop so that pointer dereferencing is
also tested */
void gen_bounded_ptr_deref(void)
{
int func;
int size, align;
Elf32_Rel *rel;
Sym *sym;
size = 0;
/* XXX: put that code in generic part of tcc */
if (!is_float(vtop->type.t)) {
if (vtop->r & VT_LVAL_BYTE)
size = 1;
else if (vtop->r & VT_LVAL_SHORT)
size = 2;
}
if (!size)
size = type_size(&vtop->type, &align);
switch(size) {
case 1: func = TOK___bound_ptr_indir1; break;
case 2: func = TOK___bound_ptr_indir2; break;
case 4: func = TOK___bound_ptr_indir4; break;
case 8: func = TOK___bound_ptr_indir8; break;
case 12: func = TOK___bound_ptr_indir12; break;
case 16: func = TOK___bound_ptr_indir16; break;
default:
error("unhandled size when derefencing bounded pointer");
func = 0;
break;
}
/* patch relocation */
/* XXX: find a better solution ? */
rel = (Elf32_Rel *)(cur_text_section->reloc->data + vtop->c.ul);
sym = external_global_sym(func, &func_old_type, 0);
if (!sym->c)
put_extern_sym(sym, NULL, 0, 0);
rel->r_info = ELF32_R_INFO(sym->c, ELF32_R_TYPE(rel->r_info));
}
#endif
/* end of X86 code generator */
/*************************************************************/
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/i386-gen.c | C | lgpl | 29,033 |
/*
* x86-64 code generator for TCC
*
* Copyright (c) 2008 Shinichiro Hamaji
*
* Based on i386-gen.c by Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <assert.h>
/* number of available registers */
#define NB_REGS 5
/* a register can belong to several classes. The classes must be
sorted from more general to more precise (see gv2() code which does
assumptions on it). */
#define RC_INT 0x0001 /* generic integer register */
#define RC_FLOAT 0x0002 /* generic float register */
#define RC_RAX 0x0004
#define RC_RCX 0x0008
#define RC_RDX 0x0010
#define RC_XMM0 0x0020
#define RC_ST0 0x0040 /* only for long double */
#define RC_IRET RC_RAX /* function return: integer register */
#define RC_LRET RC_RDX /* function return: second integer register */
#define RC_FRET RC_XMM0 /* function return: float register */
/* pretty names for the registers */
enum {
TREG_RAX = 0,
TREG_RCX = 1,
TREG_RDX = 2,
TREG_RSI = 6,
TREG_RDI = 7,
TREG_R8 = 8,
TREG_R9 = 9,
TREG_R10 = 10,
TREG_R11 = 11,
TREG_XMM0 = 3,
TREG_ST0 = 4,
TREG_MEM = 0x10,
};
#define REX_BASE(reg) (((reg) >> 3) & 1)
#define REG_VALUE(reg) ((reg) & 7)
int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_RAX,
/* ecx */ RC_INT | RC_RCX,
/* edx */ RC_INT | RC_RDX,
/* xmm0 */ RC_FLOAT | RC_XMM0,
/* st0 */ RC_ST0,
};
/* return registers for function */
#define REG_IRET TREG_RAX /* single word int return register */
#define REG_LRET TREG_RDX /* second word return register (for long long) */
#define REG_FRET TREG_XMM0 /* float return register */
/* defined if function parameters must be evaluated in reverse order */
#define INVERT_FUNC_PARAMS
/* pointer size, in bytes */
#define PTR_SIZE 8
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 16
#define LDOUBLE_ALIGN 8
/* maximum alignment (for aligned attribute support) */
#define MAX_ALIGN 8
/******************************************************/
/* ELF defines */
#define EM_TCC_TARGET EM_X86_64
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_X86_64_64
#define R_JMP_SLOT R_X86_64_JUMP_SLOT
#define R_COPY R_X86_64_COPY
#define ELF_START_ADDR 0x08048000
#define ELF_PAGE_SIZE 0x1000
/******************************************************/
static unsigned long func_sub_sp_offset;
static int func_ret_sub;
/* XXX: make it faster ? */
void g(int c)
{
int ind1;
ind1 = ind + 1;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
cur_text_section->data[ind] = c;
ind = ind1;
}
void o(unsigned int c)
{
while (c) {
g(c);
c = c >> 8;
}
}
void gen_le32(int c)
{
g(c);
g(c >> 8);
g(c >> 16);
g(c >> 24);
}
void gen_le64(int64_t c)
{
g(c);
g(c >> 8);
g(c >> 16);
g(c >> 24);
g(c >> 32);
g(c >> 40);
g(c >> 48);
g(c >> 56);
}
/* output a symbol and patch all calls to it */
void gsym_addr(int t, int a)
{
int n, *ptr;
while (t) {
ptr = (int *)(cur_text_section->data + t);
n = *ptr; /* next value */
*ptr = a - t - 4;
t = n;
}
}
void gsym(int t)
{
gsym_addr(t, ind);
}
/* psym is used to put an instruction with a data field which is a
reference to a symbol. It is in fact the same as oad ! */
#define psym oad
static int is64_type(int t)
{
return ((t & VT_BTYPE) == VT_PTR ||
(t & VT_BTYPE) == VT_FUNC ||
(t & VT_BTYPE) == VT_LLONG);
}
static int is_sse_float(int t) {
int bt;
bt = t & VT_BTYPE;
return bt == VT_DOUBLE || bt == VT_FLOAT;
}
/* instruction + 4 bytes data. Return the address of the data */
static int oad(int c, int s)
{
int ind1;
o(c);
ind1 = ind + 4;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
*(int *)(cur_text_section->data + ind) = s;
s = ind;
ind = ind1;
return s;
}
/* output constant with relocation if 'r & VT_SYM' is true */
static void gen_addr64(int r, Sym *sym, int64_t c)
{
if (r & VT_SYM)
greloc(cur_text_section, sym, ind, R_X86_64_64);
gen_le64(c);
}
/* output constant with relocation if 'r & VT_SYM' is true */
static void gen_addrpc32(int r, Sym *sym, int c)
{
if (r & VT_SYM)
greloc(cur_text_section, sym, ind, R_X86_64_PC32);
gen_le32(c-4);
}
/* output got address with relocation */
static void gen_gotpcrel(int r, Sym *sym, int c)
{
Section *sr;
ElfW(Rela) *rel;
greloc(cur_text_section, sym, ind, R_X86_64_GOTPCREL);
sr = cur_text_section->reloc;
rel = (ElfW(Rela) *)(sr->data + sr->data_offset - sizeof(ElfW(Rela)));
rel->r_addend = -4;
gen_le32(0);
if (c) {
/* we use add c, %xxx for displacement */
o(0x48 + REX_BASE(r));
o(0x81);
o(0xc0 + REG_VALUE(r));
gen_le32(c);
}
}
static void gen_modrm_impl(int op_reg, int r, Sym *sym, int c, int is_got)
{
op_reg = REG_VALUE(op_reg) << 3;
if ((r & VT_VALMASK) == VT_CONST) {
/* constant memory reference */
o(0x05 | op_reg);
if (is_got) {
gen_gotpcrel(r, sym, c);
} else {
gen_addrpc32(r, sym, c);
}
} else if ((r & VT_VALMASK) == VT_LOCAL) {
/* currently, we use only ebp as base */
if (c == (char)c) {
/* short reference */
o(0x45 | op_reg);
g(c);
} else {
oad(0x85 | op_reg, c);
}
} else if ((r & VT_VALMASK) >= TREG_MEM) {
if (c) {
g(0x80 | op_reg | REG_VALUE(r));
gen_le32(c);
} else {
g(0x00 | op_reg | REG_VALUE(r));
}
} else {
g(0x00 | op_reg | (r & VT_VALMASK));
}
}
/* generate a modrm reference. 'op_reg' contains the addtionnal 3
opcode bits */
static void gen_modrm(int op_reg, int r, Sym *sym, int c)
{
gen_modrm_impl(op_reg, r, sym, c, 0);
}
/* generate a modrm reference. 'op_reg' contains the addtionnal 3
opcode bits */
static void gen_modrm64(int opcode, int op_reg, int r, Sym *sym, int c)
{
int is_got;
int rex = 0x48 | (REX_BASE(op_reg) << 2);
if ((r & VT_VALMASK) != VT_CONST &&
(r & VT_VALMASK) != VT_LOCAL) {
rex |= REX_BASE(VT_VALMASK & r);
}
o(rex);
o(opcode);
is_got = (op_reg & TREG_MEM) && !(sym->type.t & VT_STATIC);
gen_modrm_impl(op_reg, r, sym, c, is_got);
}
/* load 'r' from value 'sv' */
void load(int r, SValue *sv)
{
int v, t, ft, fc, fr;
SValue v1;
fr = sv->r;
ft = sv->type.t;
fc = sv->c.ul;
/* we use indirect access via got */
if ((fr & VT_VALMASK) == VT_CONST && (fr & VT_SYM) &&
(fr & VT_LVAL) && !(sv->sym->type.t & VT_STATIC)) {
/* use the result register as a temporal register */
int tr = r | TREG_MEM;
if (is_float(ft)) {
/* we cannot use float registers as a temporal register */
tr = get_reg(RC_INT) | TREG_MEM;
}
gen_modrm64(0x8b, tr, fr, sv->sym, 0);
/* load from the temporal register */
fr = tr | VT_LVAL;
}
v = fr & VT_VALMASK;
if (fr & VT_LVAL) {
if (v == VT_LLOCAL) {
v1.type.t = VT_PTR;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fr = r;
}
if ((ft & VT_BTYPE) == VT_FLOAT) {
o(0x6e0f66); /* movd */
r = 0;
} else if ((ft & VT_BTYPE) == VT_DOUBLE) {
o(0x7e0ff3); /* movq */
r = 0;
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xdb); /* fldt */
r = 5;
} else if ((ft & VT_TYPE) == VT_BYTE) {
o(0xbe0f); /* movsbl */
} else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED)) {
o(0xb60f); /* movzbl */
} else if ((ft & VT_TYPE) == VT_SHORT) {
o(0xbf0f); /* movswl */
} else if ((ft & VT_TYPE) == (VT_SHORT | VT_UNSIGNED)) {
o(0xb70f); /* movzwl */
} else if (is64_type(ft)) {
gen_modrm64(0x8b, r, fr, sv->sym, fc);
return;
} else {
o(0x8b); /* movl */
}
gen_modrm(r, fr, sv->sym, fc);
} else {
if (v == VT_CONST) {
if ((ft & VT_BTYPE) == VT_LLONG) {
assert(!(fr & VT_SYM));
o(0x48);
o(0xb8 + REG_VALUE(r)); /* mov $xx, r */
gen_addr64(fr, sv->sym, sv->c.ull);
} else {
if (fr & VT_SYM) {
if (sv->sym->type.t & VT_STATIC) {
o(0x8d48);
o(0x05 + REG_VALUE(r) * 8); /* lea xx(%rip), r */
gen_addrpc32(fr, sv->sym, fc);
} else {
o(0x8b48);
o(0x05 + REG_VALUE(r) * 8); /* mov xx(%rip), r */
gen_gotpcrel(r, sv->sym, fc);
}
} else {
o(0xb8 + REG_VALUE(r)); /* mov $xx, r */
gen_le32(fc);
}
}
} else if (v == VT_LOCAL) {
o(0x48 | REX_BASE(r));
o(0x8d); /* lea xxx(%ebp), r */
gen_modrm(r, VT_LOCAL, sv->sym, fc);
} else if (v == VT_CMP) {
oad(0xb8 + r, 0); /* mov $0, r */
o(0x0f); /* setxx %br */
o(fc);
o(0xc0 + r);
} else if (v == VT_JMP || v == VT_JMPI) {
t = v & 1;
oad(0xb8 + r, t); /* mov $1, r */
o(0x05eb); /* jmp after */
gsym(fc);
oad(0xb8 + r, t ^ 1); /* mov $0, r */
} else if (v != r) {
if (r == TREG_XMM0) {
assert(v == TREG_ST0);
/* gen_cvt_ftof(VT_DOUBLE); */
o(0xf0245cdd); /* fstpl -0x10(%rsp) */
/* movsd -0x10(%rsp),%xmm0 */
o(0x44100ff2);
o(0xf024);
} else if (r == TREG_ST0) {
assert(v == TREG_XMM0);
/* gen_cvt_ftof(VT_LDOUBLE); */
/* movsd %xmm0,-0x10(%rsp) */
o(0x44110ff2);
o(0xf024);
o(0xf02444dd); /* fldl -0x10(%rsp) */
} else {
o(0x48 | REX_BASE(r) | (REX_BASE(v) << 2));
o(0x89);
o(0xc0 + r + v * 8); /* mov v, r */
}
}
}
}
/* store register 'r' in lvalue 'v' */
void store(int r, SValue *v)
{
int fr, bt, ft, fc;
int op64 = 0;
/* store the REX prefix in this variable when PIC is enabled */
int pic = 0;
ft = v->type.t;
fc = v->c.ul;
fr = v->r & VT_VALMASK;
bt = ft & VT_BTYPE;
/* we need to access the variable via got */
if (fr == VT_CONST && (v->r & VT_SYM)) {
/* mov xx(%rip), %r11 */
o(0x1d8b4c);
gen_gotpcrel(TREG_R11, v->sym, v->c.ul);
pic = is64_type(bt) ? 0x49 : 0x41;
}
/* XXX: incorrect if float reg to reg */
if (bt == VT_FLOAT) {
o(0x66);
o(pic);
o(0x7e0f); /* movd */
r = 0;
} else if (bt == VT_DOUBLE) {
o(0x66);
o(pic);
o(0xd60f); /* movq */
r = 0;
} else if (bt == VT_LDOUBLE) {
o(0xc0d9); /* fld %st(0) */
o(pic);
o(0xdb); /* fstpt */
r = 7;
} else {
if (bt == VT_SHORT)
o(0x66);
o(pic);
if (bt == VT_BYTE || bt == VT_BOOL)
o(0x88);
else if (is64_type(bt))
op64 = 0x89;
else
o(0x89);
}
if (pic) {
/* xxx r, (%r11) where xxx is mov, movq, fld, or etc */
if (op64)
o(op64);
o(3 + (r << 3));
} else if (op64) {
if (fr == VT_CONST ||
fr == VT_LOCAL ||
(v->r & VT_LVAL)) {
gen_modrm64(op64, r, v->r, v->sym, fc);
} else if (fr != r) {
/* XXX: don't we really come here? */
abort();
o(0xc0 + fr + r * 8); /* mov r, fr */
}
} else {
if (fr == VT_CONST ||
fr == VT_LOCAL ||
(v->r & VT_LVAL)) {
gen_modrm(r, v->r, v->sym, fc);
} else if (fr != r) {
/* XXX: don't we really come here? */
abort();
o(0xc0 + fr + r * 8); /* mov r, fr */
}
}
}
static void gadd_sp(int val)
{
if (val == (char)val) {
o(0xc48348);
g(val);
} else {
oad(0xc48148, val); /* add $xxx, %rsp */
}
}
/* 'is_jmp' is '1' if it is a jump */
static void gcall_or_jmp(int is_jmp)
{
int r;
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* constant case */
if (vtop->r & VT_SYM) {
/* relocation case */
greloc(cur_text_section, vtop->sym,
ind + 1, R_X86_64_PC32);
} else {
/* put an empty PC32 relocation */
put_elf_reloc(symtab_section, cur_text_section,
ind + 1, R_X86_64_PC32, 0);
}
oad(0xe8 + is_jmp, vtop->c.ul - 4); /* call/jmp im */
} else {
/* otherwise, indirect call */
r = TREG_R11;
load(r, vtop);
o(0x41); /* REX */
o(0xff); /* call/jmp *r */
o(0xd0 + REG_VALUE(r) + (is_jmp << 4));
}
}
static uint8_t arg_regs[6] = {
TREG_RDI, TREG_RSI, TREG_RDX, TREG_RCX, TREG_R8, TREG_R9
};
/* Generate function call. The function address is pushed first, then
all the parameters in call order. This functions pops all the
parameters and the function address. */
void gfunc_call(int nb_args)
{
int size, align, r, args_size, i, func_call;
Sym *func_sym;
SValue *orig_vtop;
int nb_reg_args = 0;
int nb_sse_args = 0;
int sse_reg, gen_reg;
/* calculate the number of integer/float arguments */
args_size = 0;
for(i = 0; i < nb_args; i++) {
if ((vtop[-i].type.t & VT_BTYPE) == VT_STRUCT) {
args_size += type_size(&vtop->type, &align);
} else if ((vtop[-i].type.t & VT_BTYPE) == VT_LDOUBLE) {
args_size += 16;
} else if (is_sse_float(vtop[-i].type.t)) {
nb_sse_args++;
if (nb_sse_args > 8) args_size += 8;
} else {
nb_reg_args++;
if (nb_reg_args > 6) args_size += 8;
}
}
/* for struct arguments, we need to call memcpy and the function
call breaks register passing arguments we are preparing.
So, we process arguments which will be passed by stack first. */
orig_vtop = vtop;
gen_reg = nb_reg_args;
sse_reg = nb_sse_args;
/* adjust stack to align SSE boundary */
if (args_size &= 8) {
o(0x50); /* push $rax */
}
for(i = 0; i < nb_args; i++) {
if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
size = type_size(&vtop->type, &align);
/* align to stack align size */
size = (size + 3) & ~3;
/* allocate the necessary size on stack */
o(0x48);
oad(0xec81, size); /* sub $xxx, %rsp */
/* generate structure store */
r = get_reg(RC_INT);
o(0x48 + REX_BASE(r));
o(0x89); /* mov %rsp, r */
o(0xe0 + r);
{
/* following code breaks vtop[1] */
SValue tmp = vtop[1];
vset(&vtop->type, r | VT_LVAL, 0);
vswap();
vstore();
vtop[1] = tmp;
}
args_size += size;
} else if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
gv(RC_ST0);
size = LDOUBLE_SIZE;
oad(0xec8148, size); /* sub $xxx, %rsp */
o(0x7cdb); /* fstpt 0(%rsp) */
g(0x24);
g(0x00);
args_size += size;
} else if (is_sse_float(vtop->type.t)) {
int j = --sse_reg;
if (j >= 8) {
gv(RC_FLOAT);
o(0x50); /* push $rax */
/* movq %xmm0, (%rsp) */
o(0x04d60f66);
o(0x24);
args_size += 8;
}
} else {
int j = --gen_reg;
/* simple type */
/* XXX: implicit cast ? */
if (j >= 6) {
r = gv(RC_INT);
o(0x50 + r); /* push r */
args_size += 8;
}
}
vtop--;
}
vtop = orig_vtop;
/* then, we prepare register passing arguments.
Note that we cannot set RDX and RCX in this loop because gv()
may break these temporary registers. Let's use R10 and R11
instead of them */
gen_reg = nb_reg_args;
sse_reg = nb_sse_args;
for(i = 0; i < nb_args; i++) {
if ((vtop->type.t & VT_BTYPE) == VT_STRUCT ||
(vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
} else if (is_sse_float(vtop->type.t)) {
int j = --sse_reg;
if (j < 8) {
gv(RC_FLOAT); /* only one float register */
/* movaps %xmm0, %xmmN */
o(0x280f);
o(0xc0 + (sse_reg << 3));
}
} else {
int j = --gen_reg;
/* simple type */
/* XXX: implicit cast ? */
if (j < 6) {
r = gv(RC_INT);
if (j < 2) {
o(0x8948); /* mov */
o(0xc0 + r * 8 + arg_regs[j]);
} else if (j < 4) {
o(0x8949); /* mov */
/* j=2: r10, j=3: r11 */
o(0xc0 + r * 8 + j);
} else {
o(0x8949); /* mov */
/* j=4: r8, j=5: r9 */
o(0xc0 + r * 8 + j - 4);
}
}
}
vtop--;
}
save_regs(0); /* save used temporary registers */
/* Copy R10 and R11 into RDX and RCX, respectively */
if (nb_reg_args > 2) {
o(0xd2894c); /* mov %r10, %rdx */
if (nb_reg_args > 3) {
o(0xd9894c); /* mov %r11, %rcx */
}
}
func_sym = vtop->type.ref;
func_call = FUNC_CALL(func_sym->r);
oad(0xb8, nb_sse_args < 8 ? nb_sse_args : 8); /* mov nb_sse_args, %eax */
gcall_or_jmp(0);
if (args_size)
gadd_sp(args_size);
vtop--;
}
#ifdef TCC_TARGET_PE
/* XXX: support PE? */
#warning "PE isn't tested at all"
#define FUNC_PROLOG_SIZE 12
#else
#define FUNC_PROLOG_SIZE 11
#endif
static void push_arg_reg(int i) {
loc -= 8;
gen_modrm64(0x89, arg_regs[i], VT_LOCAL, NULL, loc);
}
/* generate function prolog of type 't' */
void gfunc_prolog(CType *func_type)
{
int i, addr, align, size, func_call;
int param_index, param_addr, reg_param_index, sse_param_index;
Sym *sym;
CType *type;
func_ret_sub = 0;
sym = func_type->ref;
func_call = FUNC_CALL(sym->r);
addr = PTR_SIZE * 2;
loc = 0;
ind += FUNC_PROLOG_SIZE;
func_sub_sp_offset = ind;
if (func_type->ref->c == FUNC_ELLIPSIS) {
int seen_reg_num, seen_sse_num, seen_stack_size;
seen_reg_num = seen_sse_num = 0;
/* frame pointer and return address */
seen_stack_size = PTR_SIZE * 2;
/* count the number of seen parameters */
sym = func_type->ref;
while ((sym = sym->next) != NULL) {
type = &sym->type;
if (is_sse_float(type->t)) {
if (seen_sse_num < 8) {
seen_sse_num++;
} else {
seen_stack_size += 8;
}
} else if ((type->t & VT_BTYPE) == VT_STRUCT) {
size = type_size(type, &align);
size = (size + 3) & ~3;
seen_stack_size += size;
} else if ((type->t & VT_BTYPE) == VT_LDOUBLE) {
seen_stack_size += LDOUBLE_SIZE;
} else {
if (seen_reg_num < 6) {
seen_reg_num++;
} else {
seen_stack_size += 8;
}
}
}
loc -= 16;
/* movl $0x????????, -0x10(%rbp) */
o(0xf045c7);
gen_le32(seen_reg_num * 8);
/* movl $0x????????, -0xc(%rbp) */
o(0xf445c7);
gen_le32(seen_sse_num * 16 + 48);
/* movl $0x????????, -0x8(%rbp) */
o(0xf845c7);
gen_le32(seen_stack_size);
/* save all register passing arguments */
for (i = 0; i < 8; i++) {
loc -= 16;
o(0xd60f66); /* movq */
gen_modrm(7 - i, VT_LOCAL, NULL, loc);
/* movq $0, loc+8(%rbp) */
o(0x85c748);
gen_le32(loc + 8);
gen_le32(0);
}
for (i = 0; i < 6; i++) {
push_arg_reg(5 - i);
}
}
sym = func_type->ref;
param_index = 0;
reg_param_index = 0;
sse_param_index = 0;
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->type;
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
push_arg_reg(reg_param_index);
param_addr = loc;
func_vc = loc;
param_index++;
reg_param_index++;
}
/* define parameters */
while ((sym = sym->next) != NULL) {
type = &sym->type;
size = type_size(type, &align);
size = (size + 3) & ~3;
if (is_sse_float(type->t)) {
if (sse_param_index < 8) {
/* save arguments passed by register */
loc -= 8;
o(0xd60f66); /* movq */
gen_modrm(sse_param_index, VT_LOCAL, NULL, loc);
param_addr = loc;
} else {
param_addr = addr;
addr += size;
}
sse_param_index++;
} else if ((type->t & VT_BTYPE) == VT_STRUCT ||
(type->t & VT_BTYPE) == VT_LDOUBLE) {
param_addr = addr;
addr += size;
} else {
if (reg_param_index < 6) {
/* save arguments passed by register */
push_arg_reg(reg_param_index);
param_addr = loc;
} else {
param_addr = addr;
addr += 8;
}
reg_param_index++;
}
sym_push(sym->v & ~SYM_FIELD, type,
VT_LOCAL | VT_LVAL, param_addr);
param_index++;
}
}
/* generate function epilog */
void gfunc_epilog(void)
{
int v, saved_ind;
o(0xc9); /* leave */
if (func_ret_sub == 0) {
o(0xc3); /* ret */
} else {
o(0xc2); /* ret n */
g(func_ret_sub);
g(func_ret_sub >> 8);
}
/* align local size to word & save local variables */
v = (-loc + 15) & -16;
saved_ind = ind;
ind = func_sub_sp_offset - FUNC_PROLOG_SIZE;
#ifdef TCC_TARGET_PE
if (v >= 4096) {
Sym *sym = external_global_sym(TOK___chkstk, &func_old_type, 0);
oad(0xb8, v); /* mov stacksize, %eax */
oad(0xe8, -4); /* call __chkstk, (does the stackframe too) */
greloc(cur_text_section, sym, ind-4, R_X86_64_PC32);
} else
#endif
{
o(0xe5894855); /* push %rbp, mov %rsp, %rbp */
o(0xec8148); /* sub rsp, stacksize */
gen_le32(v);
#if FUNC_PROLOG_SIZE == 12
o(0x90); /* adjust to FUNC_PROLOG_SIZE */
#endif
}
ind = saved_ind;
}
/* generate a jump to a label */
int gjmp(int t)
{
return psym(0xe9, t);
}
/* generate a jump to a fixed address */
void gjmp_addr(int a)
{
int r;
r = a - ind - 2;
if (r == (char)r) {
g(0xeb);
g(r);
} else {
oad(0xe9, a - ind - 5);
}
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
int gtst(int inv, int t)
{
int v, *p;
v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
/* fast case : can jump directly since flags are set */
g(0x0f);
t = psym((vtop->c.i - 16) ^ inv, t);
} else if (v == VT_JMP || v == VT_JMPI) {
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
while (*p != 0)
p = (int *)(cur_text_section->data + *p);
*p = t;
t = vtop->c.i;
} else {
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->type.t) ||
(vtop->type.t & VT_BTYPE) == VT_LLONG) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
v = gv(RC_INT);
o(0x85);
o(0xc0 + v * 9);
g(0x0f);
t = psym(0x85 ^ inv, t);
}
}
vtop--;
return t;
}
/* generate an integer binary operation */
void gen_opi(int op)
{
int r, fr, opc, c;
switch(op) {
case '+':
case TOK_ADDC1: /* add with carry generation */
opc = 0;
gen_op8:
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST &&
!is64_type(vtop->type.t)) {
/* constant case */
vswap();
r = gv(RC_INT);
if (is64_type(vtop->type.t)) {
o(0x48 | REX_BASE(r));
}
vswap();
c = vtop->c.i;
if (c == (char)c) {
/* XXX: generate inc and dec for smaller code ? */
o(0x83);
o(0xc0 | (opc << 3) | REG_VALUE(r));
g(c);
} else {
o(0x81);
oad(0xc0 | (opc << 3) | REG_VALUE(r), c);
}
} else {
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
if (opc != 7 ||
is64_type(vtop[0].type.t) || (vtop[0].type.t & VT_UNSIGNED) ||
is64_type(vtop[-1].type.t) || (vtop[-1].type.t & VT_UNSIGNED)) {
o(0x48 | REX_BASE(r) | (REX_BASE(fr) << 2));
}
o((opc << 3) | 0x01);
o(0xc0 + REG_VALUE(r) + REG_VALUE(fr) * 8);
}
vtop--;
if (op >= TOK_ULT && op <= TOK_GT) {
vtop->r = VT_CMP;
vtop->c.i = op;
}
break;
case '-':
case TOK_SUBC1: /* sub with carry generation */
opc = 5;
goto gen_op8;
case TOK_ADDC2: /* add with carry use */
opc = 2;
goto gen_op8;
case TOK_SUBC2: /* sub with carry use */
opc = 3;
goto gen_op8;
case '&':
opc = 4;
goto gen_op8;
case '^':
opc = 6;
goto gen_op8;
case '|':
opc = 1;
goto gen_op8;
case '*':
gv2(RC_INT, RC_INT);
r = vtop[-1].r;
fr = vtop[0].r;
if (is64_type(vtop[0].type.t) || (vtop[0].type.t & VT_UNSIGNED) ||
is64_type(vtop[-1].type.t) || (vtop[-1].type.t & VT_UNSIGNED)) {
o(0x48 | REX_BASE(fr) | (REX_BASE(r) << 2));
}
vtop--;
o(0xaf0f); /* imul fr, r */
o(0xc0 + fr + r * 8);
break;
case TOK_SHL:
opc = 4;
goto gen_shift;
case TOK_SHR:
opc = 5;
goto gen_shift;
case TOK_SAR:
opc = 7;
gen_shift:
opc = 0xc0 | (opc << 3);
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant case */
vswap();
r = gv(RC_INT);
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
o(0x48 | REX_BASE(r));
c = 0x3f;
} else {
c = 0x1f;
}
vswap();
c &= vtop->c.i;
o(0xc1); /* shl/shr/sar $xxx, r */
o(opc | r);
g(c);
} else {
/* we generate the shift in ecx */
gv2(RC_INT, RC_RCX);
r = vtop[-1].r;
if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG) {
o(0x48 | REX_BASE(r));
}
o(0xd3); /* shl/shr/sar %cl, r */
o(opc | r);
}
vtop--;
break;
case '/':
case TOK_UDIV:
case TOK_PDIV:
case '%':
case TOK_UMOD:
case TOK_UMULL:
/* first operand must be in eax */
/* XXX: need better constraint for second operand */
gv2(RC_RAX, RC_RCX);
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
save_reg(TREG_RDX);
if (op == TOK_UMULL) {
o(0xf7); /* mul fr */
o(0xe0 + fr);
vtop->r2 = TREG_RDX;
r = TREG_RAX;
} else {
if (op == TOK_UDIV || op == TOK_UMOD) {
o(0xf7d231); /* xor %edx, %edx, div fr, %eax */
o(0xf0 + fr);
} else {
if ((vtop->type.t & VT_BTYPE) & VT_LLONG) {
o(0x9948); /* cqto */
o(0x48 + REX_BASE(fr));
} else {
o(0x99); /* cltd */
}
o(0xf7); /* idiv fr, %eax */
o(0xf8 + fr);
}
if (op == '%' || op == TOK_UMOD)
r = TREG_RDX;
else
r = TREG_RAX;
}
vtop->r = r;
break;
default:
opc = 7;
goto gen_op8;
}
}
void gen_opl(int op)
{
gen_opi(op);
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
/* XXX: need to use ST1 too */
void gen_opf(int op)
{
int a, ft, fc, swapped, r;
int float_type =
(vtop->type.t & VT_BTYPE) == VT_LDOUBLE ? RC_ST0 : RC_FLOAT;
/* convert constants to memory references */
if ((vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
vswap();
gv(float_type);
vswap();
}
if ((vtop[0].r & (VT_VALMASK | VT_LVAL)) == VT_CONST)
gv(float_type);
/* must put at least one value in the floating point register */
if ((vtop[-1].r & VT_LVAL) &&
(vtop[0].r & VT_LVAL)) {
vswap();
gv(float_type);
vswap();
}
swapped = 0;
/* swap the stack if needed so that t1 is the register and t2 is
the memory reference */
if (vtop[-1].r & VT_LVAL) {
vswap();
swapped = 1;
}
if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
if (op >= TOK_ULT && op <= TOK_GT) {
/* load on stack second operand */
load(TREG_ST0, vtop);
save_reg(TREG_RAX); /* eax is used by FP comparison code */
if (op == TOK_GE || op == TOK_GT)
swapped = !swapped;
else if (op == TOK_EQ || op == TOK_NE)
swapped = 0;
if (swapped)
o(0xc9d9); /* fxch %st(1) */
o(0xe9da); /* fucompp */
o(0xe0df); /* fnstsw %ax */
if (op == TOK_EQ) {
o(0x45e480); /* and $0x45, %ah */
o(0x40fC80); /* cmp $0x40, %ah */
} else if (op == TOK_NE) {
o(0x45e480); /* and $0x45, %ah */
o(0x40f480); /* xor $0x40, %ah */
op = TOK_NE;
} else if (op == TOK_GE || op == TOK_LE) {
o(0x05c4f6); /* test $0x05, %ah */
op = TOK_EQ;
} else {
o(0x45c4f6); /* test $0x45, %ah */
op = TOK_EQ;
}
vtop--;
vtop->r = VT_CMP;
vtop->c.i = op;
} else {
/* no memory reference possible for long double operations */
load(TREG_ST0, vtop);
swapped = !swapped;
switch(op) {
default:
case '+':
a = 0;
break;
case '-':
a = 4;
if (swapped)
a++;
break;
case '*':
a = 1;
break;
case '/':
a = 6;
if (swapped)
a++;
break;
}
ft = vtop->type.t;
fc = vtop->c.ul;
o(0xde); /* fxxxp %st, %st(1) */
o(0xc1 + (a << 3));
vtop--;
}
} else {
if (op >= TOK_ULT && op <= TOK_GT) {
/* if saved lvalue, then we must reload it */
r = vtop->r;
fc = vtop->c.ul;
if ((r & VT_VALMASK) == VT_LLOCAL) {
SValue v1;
r = get_reg(RC_INT);
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fc = 0;
}
if (op == TOK_EQ || op == TOK_NE) {
swapped = 0;
} else {
if (op == TOK_LE || op == TOK_LT)
swapped = !swapped;
if (op == TOK_LE || op == TOK_GE) {
op = 0x93; /* setae */
} else {
op = 0x97; /* seta */
}
}
if (swapped) {
o(0x7e0ff3); /* movq */
gen_modrm(1, r, vtop->sym, fc);
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
o(0x66);
}
o(0x2e0f); /* ucomisd %xmm0, %xmm1 */
o(0xc8);
} else {
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
o(0x66);
}
o(0x2e0f); /* ucomisd */
gen_modrm(0, r, vtop->sym, fc);
}
vtop--;
vtop->r = VT_CMP;
vtop->c.i = op;
} else {
/* no memory reference possible for long double operations */
if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
load(TREG_XMM0, vtop);
swapped = !swapped;
}
switch(op) {
default:
case '+':
a = 0;
break;
case '-':
a = 4;
break;
case '*':
a = 1;
break;
case '/':
a = 6;
break;
}
ft = vtop->type.t;
fc = vtop->c.ul;
if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xde); /* fxxxp %st, %st(1) */
o(0xc1 + (a << 3));
} else {
/* if saved lvalue, then we must reload it */
r = vtop->r;
if ((r & VT_VALMASK) == VT_LLOCAL) {
SValue v1;
r = get_reg(RC_INT);
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
fc = 0;
}
if (swapped) {
/* movq %xmm0,%xmm1 */
o(0x7e0ff3);
o(0xc8);
load(TREG_XMM0, vtop);
/* subsd %xmm1,%xmm0 (f2 0f 5c c1) */
if ((ft & VT_BTYPE) == VT_DOUBLE) {
o(0xf2);
} else {
o(0xf3);
}
o(0x0f);
o(0x58 + a);
o(0xc1);
} else {
if ((ft & VT_BTYPE) == VT_DOUBLE) {
o(0xf2);
} else {
o(0xf3);
}
o(0x0f);
o(0x58 + a);
gen_modrm(0, r, vtop->sym, fc);
}
}
vtop--;
}
}
}
/* convert integers to fp 't' type. Must handle 'int', 'unsigned int'
and 'long long' cases. */
void gen_cvt_itof(int t)
{
if ((t & VT_BTYPE) == VT_LDOUBLE) {
save_reg(TREG_ST0);
gv(RC_INT);
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
/* signed long long to float/double/long double (unsigned case
is handled generically) */
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x242cdf); /* fildll (%rsp) */
o(0x08c48348); /* add $8, %rsp */
} else if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
(VT_INT | VT_UNSIGNED)) {
/* unsigned int to float/double/long double */
o(0x6a); /* push $0 */
g(0x00);
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x242cdf); /* fildll (%rsp) */
o(0x10c48348); /* add $16, %rsp */
} else {
/* int to float/double/long double */
o(0x50 + (vtop->r & VT_VALMASK)); /* push r */
o(0x2404db); /* fildl (%rsp) */
o(0x08c48348); /* add $8, %rsp */
}
vtop->r = TREG_ST0;
} else {
save_reg(TREG_XMM0);
gv(RC_INT);
o(0xf2 + ((t & VT_BTYPE) == VT_FLOAT));
if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
(VT_INT | VT_UNSIGNED) ||
(vtop->type.t & VT_BTYPE) == VT_LLONG) {
o(0x48); /* REX */
}
o(0x2a0f);
o(0xc0 + (vtop->r & VT_VALMASK)); /* cvtsi2sd */
vtop->r = TREG_XMM0;
}
}
/* convert from one floating point type to another */
void gen_cvt_ftof(int t)
{
int ft, bt, tbt;
ft = vtop->type.t;
bt = ft & VT_BTYPE;
tbt = t & VT_BTYPE;
if (bt == VT_FLOAT) {
gv(RC_FLOAT);
if (tbt == VT_DOUBLE) {
o(0xc0140f); /* unpcklps */
o(0xc05a0f); /* cvtps2pd */
} else if (tbt == VT_LDOUBLE) {
/* movss %xmm0,-0x10(%rsp) */
o(0x44110ff3);
o(0xf024);
o(0xf02444d9); /* flds -0x10(%rsp) */
vtop->r = TREG_ST0;
}
} else if (bt == VT_DOUBLE) {
gv(RC_FLOAT);
if (tbt == VT_FLOAT) {
o(0xc0140f66); /* unpcklpd */
o(0xc05a0f66); /* cvtpd2ps */
} else if (tbt == VT_LDOUBLE) {
/* movsd %xmm0,-0x10(%rsp) */
o(0x44110ff2);
o(0xf024);
o(0xf02444dd); /* fldl -0x10(%rsp) */
vtop->r = TREG_ST0;
}
} else {
gv(RC_ST0);
if (tbt == VT_DOUBLE) {
o(0xf0245cdd); /* fstpl -0x10(%rsp) */
/* movsd -0x10(%rsp),%xmm0 */
o(0x44100ff2);
o(0xf024);
vtop->r = TREG_XMM0;
} else if (tbt == VT_FLOAT) {
o(0xf0245cd9); /* fstps -0x10(%rsp) */
/* movss -0x10(%rsp),%xmm0 */
o(0x44100ff3);
o(0xf024);
vtop->r = TREG_XMM0;
}
}
}
/* convert fp to int 't' type */
void gen_cvt_ftoi(int t)
{
int ft, bt, size, r;
ft = vtop->type.t;
bt = ft & VT_BTYPE;
if (bt == VT_LDOUBLE) {
gen_cvt_ftof(VT_DOUBLE);
bt = VT_DOUBLE;
}
gv(RC_FLOAT);
if (t != VT_INT)
size = 8;
else
size = 4;
r = get_reg(RC_INT);
if (bt == VT_FLOAT) {
o(0xf3);
} else if (bt == VT_DOUBLE) {
o(0xf2);
} else {
assert(0);
}
if (size == 8) {
o(0x48 + REX_BASE(r));
}
o(0x2c0f); /* cvttss2si or cvttsd2si */
o(0xc0 + (REG_VALUE(r) << 3));
vtop->r = r;
}
/* computed goto support */
void ggoto(void)
{
gcall_or_jmp(1);
vtop--;
}
/* end of x86-64 code generator */
/*************************************************************/
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/x86_64-gen.c | C | lgpl | 40,738 |
/*
* TCC - Tiny C Compiler
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
void swap(int *p, int *q)
{
int t;
t = *p;
*p = *q;
*q = t;
}
void vsetc(CType *type, int r, CValue *vc)
{
int v;
if (vtop >= vstack + (VSTACK_SIZE - 1))
error("memory full");
/* cannot let cpu flags if other instruction are generated. Also
avoid leaving VT_JMP anywhere except on the top of the stack
because it would complicate the code generator. */
if (vtop >= vstack) {
v = vtop->r & VT_VALMASK;
if (v == VT_CMP || (v & ~1) == VT_JMP)
gv(RC_INT);
}
vtop++;
vtop->type = *type;
vtop->r = r;
vtop->r2 = VT_CONST;
vtop->c = *vc;
}
/* push integer constant */
void vpushi(int v)
{
CValue cval;
cval.i = v;
vsetc(&int_type, VT_CONST, &cval);
}
/* push long long constant */
void vpushll(long long v)
{
CValue cval;
CType ctype;
ctype.t = VT_LLONG;
cval.ull = v;
vsetc(&ctype, VT_CONST, &cval);
}
/* Return a static symbol pointing to a section */
static Sym *get_sym_ref(CType *type, Section *sec,
unsigned long offset, unsigned long size)
{
int v;
Sym *sym;
v = anon_sym++;
sym = global_identifier_push(v, type->t | VT_STATIC, 0);
sym->type.ref = type->ref;
sym->r = VT_CONST | VT_SYM;
put_extern_sym(sym, sec, offset, size);
return sym;
}
/* push a reference to a section offset by adding a dummy symbol */
static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
{
CValue cval;
cval.ul = 0;
vsetc(type, VT_CONST | VT_SYM, &cval);
vtop->sym = get_sym_ref(type, sec, offset, size);
}
/* define a new external reference to a symbol 'v' of type 'u' */
static Sym *external_global_sym(int v, CType *type, int r)
{
Sym *s;
s = sym_find(v);
if (!s) {
/* push forward reference */
s = global_identifier_push(v, type->t | VT_EXTERN, 0);
s->type.ref = type->ref;
s->r = r | VT_CONST | VT_SYM;
}
return s;
}
/* define a new external reference to a symbol 'v' of type 'u' */
static Sym *external_sym(int v, CType *type, int r)
{
Sym *s;
s = sym_find(v);
if (!s) {
/* push forward reference */
s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
s->type.t |= VT_EXTERN;
} else {
if (!is_compatible_types(&s->type, type))
error("incompatible types for redefinition of '%s'",
get_tok_str(v, NULL));
}
return s;
}
/* push a reference to global symbol v */
static void vpush_global_sym(CType *type, int v)
{
Sym *sym;
CValue cval;
sym = external_global_sym(v, type, 0);
cval.ul = 0;
vsetc(type, VT_CONST | VT_SYM, &cval);
vtop->sym = sym;
}
void vset(CType *type, int r, int v)
{
CValue cval;
cval.i = v;
vsetc(type, r, &cval);
}
void vseti(int r, int v)
{
CType type;
type.t = VT_INT;
vset(&type, r, v);
}
void vswap(void)
{
SValue tmp;
tmp = vtop[0];
vtop[0] = vtop[-1];
vtop[-1] = tmp;
}
void vpushv(SValue *v)
{
if (vtop >= vstack + (VSTACK_SIZE - 1))
error("memory full");
vtop++;
*vtop = *v;
}
void vdup(void)
{
vpushv(vtop);
}
/* save r to the memory stack, and mark it as being free */
void save_reg(int r)
{
int l, saved, size, align;
SValue *p, sv;
CType *type;
/* modify all stack values */
saved = 0;
l = 0;
for(p=vstack;p<=vtop;p++) {
if ((p->r & VT_VALMASK) == r ||
((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
/* must save value on stack if not already done */
if (!saved) {
/* NOTE: must reload 'r' because r might be equal to r2 */
r = p->r & VT_VALMASK;
/* store register in the stack */
type = &p->type;
if ((p->r & VT_LVAL) ||
(!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
#ifdef TCC_TARGET_X86_64
type = &char_pointer_type;
#else
type = &int_type;
#endif
size = type_size(type, &align);
loc = (loc - size) & -align;
sv.type.t = type->t;
sv.r = VT_LOCAL | VT_LVAL;
sv.c.ul = loc;
store(r, &sv);
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
/* x86 specific: need to pop fp register ST0 if saved */
if (r == TREG_ST0) {
o(0xd9dd); /* fstp %st(1) */
}
#endif
#ifndef TCC_TARGET_X86_64
/* special long long case */
if ((type->t & VT_BTYPE) == VT_LLONG) {
sv.c.ul += 4;
store(p->r2, &sv);
}
#endif
l = loc;
saved = 1;
}
/* mark that stack entry as being saved on the stack */
if (p->r & VT_LVAL) {
/* also clear the bounded flag because the
relocation address of the function was stored in
p->c.ul */
p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
} else {
p->r = lvalue_type(p->type.t) | VT_LOCAL;
}
p->r2 = VT_CONST;
p->c.ul = l;
}
}
}
/* find a register of class 'rc2' with at most one reference on stack.
* If none, call get_reg(rc) */
int get_reg_ex(int rc, int rc2)
{
int r;
SValue *p;
for(r=0;r<NB_REGS;r++) {
if (reg_classes[r] & rc2) {
int n;
n=0;
for(p = vstack; p <= vtop; p++) {
if ((p->r & VT_VALMASK) == r ||
(p->r2 & VT_VALMASK) == r)
n++;
}
if (n <= 1)
return r;
}
}
return get_reg(rc);
}
/* find a free register of class 'rc'. If none, save one register */
int get_reg(int rc)
{
int r;
SValue *p;
/* find a free register */
for(r=0;r<NB_REGS;r++) {
if (reg_classes[r] & rc) {
for(p=vstack;p<=vtop;p++) {
if ((p->r & VT_VALMASK) == r ||
(p->r2 & VT_VALMASK) == r)
goto notfound;
}
return r;
}
notfound: ;
}
/* no register left : free the first one on the stack (VERY
IMPORTANT to start from the bottom to ensure that we don't
spill registers used in gen_opi()) */
for(p=vstack;p<=vtop;p++) {
r = p->r & VT_VALMASK;
if (r < VT_CONST && (reg_classes[r] & rc))
goto save_found;
/* also look at second register (if long long) */
r = p->r2 & VT_VALMASK;
if (r < VT_CONST && (reg_classes[r] & rc)) {
save_found:
save_reg(r);
return r;
}
}
/* Should never comes here */
return -1;
}
/* save registers up to (vtop - n) stack entry */
void save_regs(int n)
{
int r;
SValue *p, *p1;
p1 = vtop - n;
for(p = vstack;p <= p1; p++) {
r = p->r & VT_VALMASK;
if (r < VT_CONST) {
save_reg(r);
}
}
}
/* move register 's' to 'r', and flush previous value of r to memory
if needed */
void move_reg(int r, int s)
{
SValue sv;
if (r != s) {
save_reg(r);
sv.type.t = VT_INT;
sv.r = s;
sv.c.ul = 0;
load(r, &sv);
}
}
/* get address of vtop (vtop MUST BE an lvalue) */
void gaddrof(void)
{
vtop->r &= ~VT_LVAL;
/* tricky: if saved lvalue, then we can go back to lvalue */
if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
}
#ifdef CONFIG_TCC_BCHECK
/* generate lvalue bound code */
void gbound(void)
{
int lval_type;
CType type1;
vtop->r &= ~VT_MUSTBOUND;
/* if lvalue, then use checking code before dereferencing */
if (vtop->r & VT_LVAL) {
/* if not VT_BOUNDED value, then make one */
if (!(vtop->r & VT_BOUNDED)) {
lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
/* must save type because we must set it to int to get pointer */
type1 = vtop->type;
vtop->type.t = VT_INT;
gaddrof();
vpushi(0);
gen_bounded_ptr_add();
vtop->r |= lval_type;
vtop->type = type1;
}
/* then check for dereferencing */
gen_bounded_ptr_deref();
}
}
#endif
/* store vtop a register belonging to class 'rc'. lvalues are
converted to values. Cannot be used if cannot be converted to
register value (such as structures). */
int gv(int rc)
{
int r, rc2, bit_pos, bit_size, size, align, i;
/* NOTE: get_reg can modify vstack[] */
if (vtop->type.t & VT_BITFIELD) {
CType type;
int bits = 32;
bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
/* remove bit field info to avoid loops */
vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
/* cast to int to propagate signedness in following ops */
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
type.t = VT_LLONG;
bits = 64;
} else
type.t = VT_INT;
if((vtop->type.t & VT_UNSIGNED) ||
(vtop->type.t & VT_BTYPE) == VT_BOOL)
type.t |= VT_UNSIGNED;
gen_cast(&type);
/* generate shifts */
vpushi(bits - (bit_pos + bit_size));
gen_op(TOK_SHL);
vpushi(bits - bit_size);
/* NOTE: transformed to SHR if unsigned */
gen_op(TOK_SAR);
r = gv(rc);
} else {
if (is_float(vtop->type.t) &&
(vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
Sym *sym;
int *ptr;
unsigned long offset;
#if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
CValue check;
#endif
/* XXX: unify with initializers handling ? */
/* CPUs usually cannot use float constants, so we store them
generically in data segment */
size = type_size(&vtop->type, &align);
offset = (data_section->data_offset + align - 1) & -align;
data_section->data_offset = offset;
/* XXX: not portable yet */
#if defined(__i386__) || defined(__x86_64__)
/* Zero pad x87 tenbyte long doubles */
if (size == LDOUBLE_SIZE)
vtop->c.tab[2] &= 0xffff;
#endif
ptr = section_ptr_add(data_section, size);
size = size >> 2;
#if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
check.d = 1;
if(check.tab[0])
for(i=0;i<size;i++)
ptr[i] = vtop->c.tab[size-1-i];
else
#endif
for(i=0;i<size;i++)
ptr[i] = vtop->c.tab[i];
sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
vtop->r |= VT_LVAL | VT_SYM;
vtop->sym = sym;
vtop->c.ul = 0;
}
#ifdef CONFIG_TCC_BCHECK
if (vtop->r & VT_MUSTBOUND)
gbound();
#endif
r = vtop->r & VT_VALMASK;
rc2 = RC_INT;
if (rc == RC_IRET)
rc2 = RC_LRET;
/* need to reload if:
- constant
- lvalue (need to dereference pointer)
- already a register, but not in the right class */
if (r >= VT_CONST ||
(vtop->r & VT_LVAL) ||
!(reg_classes[r] & rc) ||
((vtop->type.t & VT_BTYPE) == VT_LLONG &&
!(reg_classes[vtop->r2] & rc2))) {
r = get_reg(rc);
#ifndef TCC_TARGET_X86_64
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
int r2;
unsigned long long ll;
/* two register type load : expand to two words
temporarily */
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* load constant */
ll = vtop->c.ull;
vtop->c.ui = ll; /* first word */
load(r, vtop);
vtop->r = r; /* save register value */
vpushi(ll >> 32); /* second word */
} else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
(vtop->r & VT_LVAL)) {
/* We do not want to modifier the long long
pointer here, so the safest (and less
efficient) is to save all the other registers
in the stack. XXX: totally inefficient. */
save_regs(1);
/* load from memory */
load(r, vtop);
vdup();
vtop[-1].r = r; /* save register value */
/* increment pointer to get second word */
vtop->type.t = VT_INT;
gaddrof();
vpushi(4);
gen_op('+');
vtop->r |= VT_LVAL;
} else {
/* move registers */
load(r, vtop);
vdup();
vtop[-1].r = r; /* save register value */
vtop->r = vtop[-1].r2;
}
/* allocate second register */
r2 = get_reg(rc2);
load(r2, vtop);
vpop();
/* write second register */
vtop->r2 = r2;
} else
#endif
if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
int t1, t;
/* lvalue of scalar type : need to use lvalue type
because of possible cast */
t = vtop->type.t;
t1 = t;
/* compute memory access type */
if (vtop->r & VT_LVAL_BYTE)
t = VT_BYTE;
else if (vtop->r & VT_LVAL_SHORT)
t = VT_SHORT;
if (vtop->r & VT_LVAL_UNSIGNED)
t |= VT_UNSIGNED;
vtop->type.t = t;
load(r, vtop);
/* restore wanted type */
vtop->type.t = t1;
} else {
/* one register type load */
load(r, vtop);
}
}
vtop->r = r;
#ifdef TCC_TARGET_C67
/* uses register pairs for doubles */
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
vtop->r2 = r+1;
#endif
}
return r;
}
/* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
void gv2(int rc1, int rc2)
{
int v;
/* generate more generic register first. But VT_JMP or VT_CMP
values must be generated first in all cases to avoid possible
reload errors */
v = vtop[0].r & VT_VALMASK;
if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
vswap();
gv(rc1);
vswap();
gv(rc2);
/* test if reload is needed for first register */
if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
vswap();
gv(rc1);
vswap();
}
} else {
gv(rc2);
vswap();
gv(rc1);
vswap();
/* test if reload is needed for first register */
if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
gv(rc2);
}
}
}
/* wrapper around RC_FRET to return a register by type */
int rc_fret(int t)
{
#ifdef TCC_TARGET_X86_64
if (t == VT_LDOUBLE) {
return RC_ST0;
}
#endif
return RC_FRET;
}
/* wrapper around REG_FRET to return a register by type */
int reg_fret(int t)
{
#ifdef TCC_TARGET_X86_64
if (t == VT_LDOUBLE) {
return TREG_ST0;
}
#endif
return REG_FRET;
}
/* expand long long on stack in two int registers */
void lexpand(void)
{
int u;
u = vtop->type.t & VT_UNSIGNED;
gv(RC_INT);
vdup();
vtop[0].r = vtop[-1].r2;
vtop[0].r2 = VT_CONST;
vtop[-1].r2 = VT_CONST;
vtop[0].type.t = VT_INT | u;
vtop[-1].type.t = VT_INT | u;
}
#ifdef TCC_TARGET_ARM
/* expand long long on stack */
void lexpand_nr(void)
{
int u,v;
u = vtop->type.t & VT_UNSIGNED;
vdup();
vtop->r2 = VT_CONST;
vtop->type.t = VT_INT | u;
v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
if (v == VT_CONST) {
vtop[-1].c.ui = vtop->c.ull;
vtop->c.ui = vtop->c.ull >> 32;
vtop->r = VT_CONST;
} else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
vtop->c.ui += 4;
vtop->r = vtop[-1].r;
} else if (v > VT_CONST) {
vtop--;
lexpand();
} else
vtop->r = vtop[-1].r2;
vtop[-1].r2 = VT_CONST;
vtop[-1].type.t = VT_INT | u;
}
#endif
/* build a long long from two ints */
void lbuild(int t)
{
gv2(RC_INT, RC_INT);
vtop[-1].r2 = vtop[0].r;
vtop[-1].type.t = t;
vpop();
}
/* rotate n first stack elements to the bottom
I1 ... In -> I2 ... In I1 [top is right]
*/
void vrotb(int n)
{
int i;
SValue tmp;
tmp = vtop[-n + 1];
for(i=-n+1;i!=0;i++)
vtop[i] = vtop[i+1];
vtop[0] = tmp;
}
/* rotate n first stack elements to the top
I1 ... In -> In I1 ... I(n-1) [top is right]
*/
void vrott(int n)
{
int i;
SValue tmp;
tmp = vtop[0];
for(i = 0;i < n - 1; i++)
vtop[-i] = vtop[-i - 1];
vtop[-n + 1] = tmp;
}
#ifdef TCC_TARGET_ARM
/* like vrott but in other direction
In ... I1 -> I(n-1) ... I1 In [top is right]
*/
void vnrott(int n)
{
int i;
SValue tmp;
tmp = vtop[-n + 1];
for(i = n - 1; i > 0; i--)
vtop[-i] = vtop[-i + 1];
vtop[0] = tmp;
}
#endif
/* pop stack value */
void vpop(void)
{
int v;
v = vtop->r & VT_VALMASK;
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
/* for x86, we need to pop the FP stack */
if (v == TREG_ST0 && !nocode_wanted) {
o(0xd9dd); /* fstp %st(1) */
} else
#endif
if (v == VT_JMP || v == VT_JMPI) {
/* need to put correct jump if && or || without test */
gsym(vtop->c.ul);
}
vtop--;
}
/* convert stack entry to register and duplicate its value in another
register */
void gv_dup(void)
{
int rc, t, r, r1;
SValue sv;
t = vtop->type.t;
if ((t & VT_BTYPE) == VT_LLONG) {
lexpand();
gv_dup();
vswap();
vrotb(3);
gv_dup();
vrotb(4);
/* stack: H L L1 H1 */
lbuild(t);
vrotb(3);
vrotb(3);
vswap();
lbuild(t);
vswap();
} else {
/* duplicate value */
rc = RC_INT;
sv.type.t = VT_INT;
if (is_float(t)) {
rc = RC_FLOAT;
#ifdef TCC_TARGET_X86_64
if ((t & VT_BTYPE) == VT_LDOUBLE) {
rc = RC_ST0;
}
#endif
sv.type.t = t;
}
r = gv(rc);
r1 = get_reg(rc);
sv.r = r;
sv.c.ul = 0;
load(r1, &sv); /* move r to r1 */
vdup();
/* duplicates value */
vtop->r = r1;
}
}
#ifndef TCC_TARGET_X86_64
/* generate CPU independent (unsigned) long long operations */
void gen_opl(int op)
{
int t, a, b, op1, c, i;
int func;
unsigned short reg_iret = REG_IRET;
unsigned short reg_lret = REG_LRET;
SValue tmp;
switch(op) {
case '/':
case TOK_PDIV:
func = TOK___divdi3;
goto gen_func;
case TOK_UDIV:
func = TOK___udivdi3;
goto gen_func;
case '%':
func = TOK___moddi3;
goto gen_mod_func;
case TOK_UMOD:
func = TOK___umoddi3;
gen_mod_func:
#ifdef TCC_ARM_EABI
reg_iret = TREG_R2;
reg_lret = TREG_R3;
#endif
gen_func:
/* call generic long long function */
vpush_global_sym(&func_old_type, func);
vrott(3);
gfunc_call(2);
vpushi(0);
vtop->r = reg_iret;
vtop->r2 = reg_lret;
break;
case '^':
case '&':
case '|':
case '*':
case '+':
case '-':
t = vtop->type.t;
vswap();
lexpand();
vrotb(3);
lexpand();
/* stack: L1 H1 L2 H2 */
tmp = vtop[0];
vtop[0] = vtop[-3];
vtop[-3] = tmp;
tmp = vtop[-2];
vtop[-2] = vtop[-3];
vtop[-3] = tmp;
vswap();
/* stack: H1 H2 L1 L2 */
if (op == '*') {
vpushv(vtop - 1);
vpushv(vtop - 1);
gen_op(TOK_UMULL);
lexpand();
/* stack: H1 H2 L1 L2 ML MH */
for(i=0;i<4;i++)
vrotb(6);
/* stack: ML MH H1 H2 L1 L2 */
tmp = vtop[0];
vtop[0] = vtop[-2];
vtop[-2] = tmp;
/* stack: ML MH H1 L2 H2 L1 */
gen_op('*');
vrotb(3);
vrotb(3);
gen_op('*');
/* stack: ML MH M1 M2 */
gen_op('+');
gen_op('+');
} else if (op == '+' || op == '-') {
/* XXX: add non carry method too (for MIPS or alpha) */
if (op == '+')
op1 = TOK_ADDC1;
else
op1 = TOK_SUBC1;
gen_op(op1);
/* stack: H1 H2 (L1 op L2) */
vrotb(3);
vrotb(3);
gen_op(op1 + 1); /* TOK_xxxC2 */
} else {
gen_op(op);
/* stack: H1 H2 (L1 op L2) */
vrotb(3);
vrotb(3);
/* stack: (L1 op L2) H1 H2 */
gen_op(op);
/* stack: (L1 op L2) (H1 op H2) */
}
/* stack: L H */
lbuild(t);
break;
case TOK_SAR:
case TOK_SHR:
case TOK_SHL:
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
t = vtop[-1].type.t;
vswap();
lexpand();
vrotb(3);
/* stack: L H shift */
c = (int)vtop->c.i;
/* constant: simpler */
/* NOTE: all comments are for SHL. the other cases are
done by swaping words */
vpop();
if (op != TOK_SHL)
vswap();
if (c >= 32) {
/* stack: L H */
vpop();
if (c > 32) {
vpushi(c - 32);
gen_op(op);
}
if (op != TOK_SAR) {
vpushi(0);
} else {
gv_dup();
vpushi(31);
gen_op(TOK_SAR);
}
vswap();
} else {
vswap();
gv_dup();
/* stack: H L L */
vpushi(c);
gen_op(op);
vswap();
vpushi(32 - c);
if (op == TOK_SHL)
gen_op(TOK_SHR);
else
gen_op(TOK_SHL);
vrotb(3);
/* stack: L L H */
vpushi(c);
if (op == TOK_SHL)
gen_op(TOK_SHL);
else
gen_op(TOK_SHR);
gen_op('|');
}
if (op != TOK_SHL)
vswap();
lbuild(t);
} else {
/* XXX: should provide a faster fallback on x86 ? */
switch(op) {
case TOK_SAR:
func = TOK___ashrdi3;
goto gen_func;
case TOK_SHR:
func = TOK___lshrdi3;
goto gen_func;
case TOK_SHL:
func = TOK___ashldi3;
goto gen_func;
}
}
break;
default:
/* compare operations */
t = vtop->type.t;
vswap();
lexpand();
vrotb(3);
lexpand();
/* stack: L1 H1 L2 H2 */
tmp = vtop[-1];
vtop[-1] = vtop[-2];
vtop[-2] = tmp;
/* stack: L1 L2 H1 H2 */
/* compare high */
op1 = op;
/* when values are equal, we need to compare low words. since
the jump is inverted, we invert the test too. */
if (op1 == TOK_LT)
op1 = TOK_LE;
else if (op1 == TOK_GT)
op1 = TOK_GE;
else if (op1 == TOK_ULT)
op1 = TOK_ULE;
else if (op1 == TOK_UGT)
op1 = TOK_UGE;
a = 0;
b = 0;
gen_op(op1);
if (op1 != TOK_NE) {
a = gtst(1, 0);
}
if (op != TOK_EQ) {
/* generate non equal test */
/* XXX: NOT PORTABLE yet */
if (a == 0) {
b = gtst(0, 0);
} else {
#if defined(TCC_TARGET_I386)
b = psym(0x850f, 0);
#elif defined(TCC_TARGET_ARM)
b = ind;
o(0x1A000000 | encbranch(ind, 0, 1));
#elif defined(TCC_TARGET_C67)
error("not implemented");
#else
#error not supported
#endif
}
}
/* compare low. Always unsigned */
op1 = op;
if (op1 == TOK_LT)
op1 = TOK_ULT;
else if (op1 == TOK_LE)
op1 = TOK_ULE;
else if (op1 == TOK_GT)
op1 = TOK_UGT;
else if (op1 == TOK_GE)
op1 = TOK_UGE;
gen_op(op1);
a = gtst(1, a);
gsym(b);
vseti(VT_JMPI, a);
break;
}
}
#endif
/* handle integer constant optimizations and various machine
independent opt */
void gen_opic(int op)
{
int c1, c2, t1, t2, n;
SValue *v1, *v2;
long long l1, l2;
typedef unsigned long long U;
v1 = vtop - 1;
v2 = vtop;
t1 = v1->type.t & VT_BTYPE;
t2 = v2->type.t & VT_BTYPE;
if (t1 == VT_LLONG)
l1 = v1->c.ll;
else if (v1->type.t & VT_UNSIGNED)
l1 = v1->c.ui;
else
l1 = v1->c.i;
if (t2 == VT_LLONG)
l2 = v2->c.ll;
else if (v2->type.t & VT_UNSIGNED)
l2 = v2->c.ui;
else
l2 = v2->c.i;
/* currently, we cannot do computations with forward symbols */
c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
if (c1 && c2) {
switch(op) {
case '+': l1 += l2; break;
case '-': l1 -= l2; break;
case '&': l1 &= l2; break;
case '^': l1 ^= l2; break;
case '|': l1 |= l2; break;
case '*': l1 *= l2; break;
case TOK_PDIV:
case '/':
case '%':
case TOK_UDIV:
case TOK_UMOD:
/* if division by zero, generate explicit division */
if (l2 == 0) {
if (const_wanted)
error("division by zero in constant");
goto general_case;
}
switch(op) {
default: l1 /= l2; break;
case '%': l1 %= l2; break;
case TOK_UDIV: l1 = (U)l1 / l2; break;
case TOK_UMOD: l1 = (U)l1 % l2; break;
}
break;
case TOK_SHL: l1 <<= l2; break;
case TOK_SHR: l1 = (U)l1 >> l2; break;
case TOK_SAR: l1 >>= l2; break;
/* tests */
case TOK_ULT: l1 = (U)l1 < (U)l2; break;
case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
case TOK_EQ: l1 = l1 == l2; break;
case TOK_NE: l1 = l1 != l2; break;
case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
case TOK_UGT: l1 = (U)l1 > (U)l2; break;
case TOK_LT: l1 = l1 < l2; break;
case TOK_GE: l1 = l1 >= l2; break;
case TOK_LE: l1 = l1 <= l2; break;
case TOK_GT: l1 = l1 > l2; break;
/* logical */
case TOK_LAND: l1 = l1 && l2; break;
case TOK_LOR: l1 = l1 || l2; break;
default:
goto general_case;
}
v1->c.ll = l1;
vtop--;
} else {
/* if commutative ops, put c2 as constant */
if (c1 && (op == '+' || op == '&' || op == '^' ||
op == '|' || op == '*')) {
vswap();
c2 = c1; //c = c1, c1 = c2, c2 = c;
l2 = l1; //l = l1, l1 = l2, l2 = l;
}
/* Filter out NOP operations like x*1, x-0, x&-1... */
if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
op == TOK_PDIV) &&
l2 == 1) ||
((op == '+' || op == '-' || op == '|' || op == '^' ||
op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
l2 == 0) ||
(op == '&' &&
l2 == -1))) {
/* nothing to do */
vtop--;
} else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
/* try to use shifts instead of muls or divs */
if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
n = -1;
while (l2) {
l2 >>= 1;
n++;
}
vtop->c.ll = n;
if (op == '*')
op = TOK_SHL;
else if (op == TOK_PDIV)
op = TOK_SAR;
else
op = TOK_SHR;
}
goto general_case;
} else if (c2 && (op == '+' || op == '-') &&
((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
(VT_CONST | VT_SYM) ||
(vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
/* symbol + constant case */
if (op == '-')
l2 = -l2;
vtop--;
vtop->c.ll += l2;
} else {
general_case:
if (!nocode_wanted) {
/* call low level op generator */
if (t1 == VT_LLONG || t2 == VT_LLONG)
gen_opl(op);
else
gen_opi(op);
} else {
vtop--;
}
}
}
}
/* generate a floating point operation with constant propagation */
void gen_opif(int op)
{
int c1, c2;
SValue *v1, *v2;
long double f1, f2;
v1 = vtop - 1;
v2 = vtop;
/* currently, we cannot do computations with forward symbols */
c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
if (c1 && c2) {
if (v1->type.t == VT_FLOAT) {
f1 = v1->c.f;
f2 = v2->c.f;
} else if (v1->type.t == VT_DOUBLE) {
f1 = v1->c.d;
f2 = v2->c.d;
} else {
f1 = v1->c.ld;
f2 = v2->c.ld;
}
/* NOTE: we only do constant propagation if finite number (not
NaN or infinity) (ANSI spec) */
if (!ieee_finite(f1) || !ieee_finite(f2))
goto general_case;
switch(op) {
case '+': f1 += f2; break;
case '-': f1 -= f2; break;
case '*': f1 *= f2; break;
case '/':
if (f2 == 0.0) {
if (const_wanted)
error("division by zero in constant");
goto general_case;
}
f1 /= f2;
break;
/* XXX: also handles tests ? */
default:
goto general_case;
}
/* XXX: overflow test ? */
if (v1->type.t == VT_FLOAT) {
v1->c.f = f1;
} else if (v1->type.t == VT_DOUBLE) {
v1->c.d = f1;
} else {
v1->c.ld = f1;
}
vtop--;
} else {
general_case:
if (!nocode_wanted) {
gen_opf(op);
} else {
vtop--;
}
}
}
static int pointed_size(CType *type)
{
int align;
return type_size(pointed_type(type), &align);
}
static inline int is_null_pointer(SValue *p)
{
if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
return 0;
return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
}
static inline int is_integer_btype(int bt)
{
return (bt == VT_BYTE || bt == VT_SHORT ||
bt == VT_INT || bt == VT_LLONG);
}
/* check types for comparison or substraction of pointers */
static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
{
CType *type1, *type2, tmp_type1, tmp_type2;
int bt1, bt2;
/* null pointers are accepted for all comparisons as gcc */
if (is_null_pointer(p1) || is_null_pointer(p2))
return;
type1 = &p1->type;
type2 = &p2->type;
bt1 = type1->t & VT_BTYPE;
bt2 = type2->t & VT_BTYPE;
/* accept comparison between pointer and integer with a warning */
if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
if (op != TOK_LOR && op != TOK_LAND )
warning("comparison between pointer and integer");
return;
}
/* both must be pointers or implicit function pointers */
if (bt1 == VT_PTR) {
type1 = pointed_type(type1);
} else if (bt1 != VT_FUNC)
goto invalid_operands;
if (bt2 == VT_PTR) {
type2 = pointed_type(type2);
} else if (bt2 != VT_FUNC) {
invalid_operands:
error("invalid operands to binary %s", get_tok_str(op, NULL));
}
if ((type1->t & VT_BTYPE) == VT_VOID ||
(type2->t & VT_BTYPE) == VT_VOID)
return;
tmp_type1 = *type1;
tmp_type2 = *type2;
tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
/* gcc-like error if '-' is used */
if (op == '-')
goto invalid_operands;
else
warning("comparison of distinct pointer types lacks a cast");
}
}
/* generic gen_op: handles types problems */
void gen_op(int op)
{
int u, t1, t2, bt1, bt2, t;
CType type1;
t1 = vtop[-1].type.t;
t2 = vtop[0].type.t;
bt1 = t1 & VT_BTYPE;
bt2 = t2 & VT_BTYPE;
if (bt1 == VT_PTR || bt2 == VT_PTR) {
/* at least one operand is a pointer */
/* relationnal op: must be both pointers */
if (op >= TOK_ULT && op <= TOK_LOR) {
check_comparison_pointer_types(vtop - 1, vtop, op);
/* pointers are handled are unsigned */
#ifdef TCC_TARGET_X86_64
t = VT_LLONG | VT_UNSIGNED;
#else
t = VT_INT | VT_UNSIGNED;
#endif
goto std_op;
}
/* if both pointers, then it must be the '-' op */
if (bt1 == VT_PTR && bt2 == VT_PTR) {
if (op != '-')
error("cannot use pointers here");
check_comparison_pointer_types(vtop - 1, vtop, op);
/* XXX: check that types are compatible */
u = pointed_size(&vtop[-1].type);
gen_opic(op);
/* set to integer type */
#ifdef TCC_TARGET_X86_64
vtop->type.t = VT_LLONG;
#else
vtop->type.t = VT_INT;
#endif
vpushi(u);
gen_op(TOK_PDIV);
} else {
/* exactly one pointer : must be '+' or '-'. */
if (op != '-' && op != '+')
error("cannot use pointers here");
/* Put pointer as first operand */
if (bt2 == VT_PTR) {
vswap();
swap(&t1, &t2);
}
type1 = vtop[-1].type;
#ifdef TCC_TARGET_X86_64
vpushll(pointed_size(&vtop[-1].type));
#else
/* XXX: cast to int ? (long long case) */
vpushi(pointed_size(&vtop[-1].type));
#endif
gen_op('*');
#ifdef CONFIG_TCC_BCHECK
/* if evaluating constant expression, no code should be
generated, so no bound check */
if (tcc_state->do_bounds_check && !const_wanted) {
/* if bounded pointers, we generate a special code to
test bounds */
if (op == '-') {
vpushi(0);
vswap();
gen_op('-');
}
gen_bounded_ptr_add();
} else
#endif
{
gen_opic(op);
}
/* put again type if gen_opic() swaped operands */
vtop->type = type1;
}
} else if (is_float(bt1) || is_float(bt2)) {
/* compute bigger type and do implicit casts */
if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
t = VT_LDOUBLE;
} else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
t = VT_DOUBLE;
} else {
t = VT_FLOAT;
}
/* floats can only be used for a few operations */
if (op != '+' && op != '-' && op != '*' && op != '/' &&
(op < TOK_ULT || op > TOK_GT))
error("invalid operands for binary operation");
goto std_op;
} else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
/* cast to biggest op */
t = VT_LLONG;
/* convert to unsigned if it does not fit in a long long */
if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
(t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
t |= VT_UNSIGNED;
goto std_op;
} else {
/* integer operations */
t = VT_INT;
/* convert to unsigned if it does not fit in an integer */
if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
(t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
t |= VT_UNSIGNED;
std_op:
/* XXX: currently, some unsigned operations are explicit, so
we modify them here */
if (t & VT_UNSIGNED) {
if (op == TOK_SAR)
op = TOK_SHR;
else if (op == '/')
op = TOK_UDIV;
else if (op == '%')
op = TOK_UMOD;
else if (op == TOK_LT)
op = TOK_ULT;
else if (op == TOK_GT)
op = TOK_UGT;
else if (op == TOK_LE)
op = TOK_ULE;
else if (op == TOK_GE)
op = TOK_UGE;
}
vswap();
type1.t = t;
gen_cast(&type1);
vswap();
/* special case for shifts and long long: we keep the shift as
an integer */
if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
type1.t = VT_INT;
gen_cast(&type1);
if (is_float(t))
gen_opif(op);
else
gen_opic(op);
if (op >= TOK_ULT && op <= TOK_GT) {
/* relationnal op: the result is an int */
vtop->type.t = VT_INT;
} else {
vtop->type.t = t;
}
}
}
#ifndef TCC_TARGET_ARM
/* generic itof for unsigned long long case */
void gen_cvt_itof1(int t)
{
if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
(VT_LLONG | VT_UNSIGNED)) {
if (t == VT_FLOAT)
vpush_global_sym(&func_old_type, TOK___floatundisf);
#if LDOUBLE_SIZE != 8
else if (t == VT_LDOUBLE)
vpush_global_sym(&func_old_type, TOK___floatundixf);
#endif
else
vpush_global_sym(&func_old_type, TOK___floatundidf);
vrott(2);
gfunc_call(1);
vpushi(0);
vtop->r = reg_fret(t);
} else {
gen_cvt_itof(t);
}
}
#endif
/* generic ftoi for unsigned long long case */
void gen_cvt_ftoi1(int t)
{
int st;
if (t == (VT_LLONG | VT_UNSIGNED)) {
/* not handled natively */
st = vtop->type.t & VT_BTYPE;
if (st == VT_FLOAT)
vpush_global_sym(&func_old_type, TOK___fixunssfdi);
#if LDOUBLE_SIZE != 8
else if (st == VT_LDOUBLE)
vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
#endif
else
vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
vrott(2);
gfunc_call(1);
vpushi(0);
vtop->r = REG_IRET;
vtop->r2 = REG_LRET;
} else {
gen_cvt_ftoi(t);
}
}
/* force char or short cast */
void force_charshort_cast(int t)
{
int bits, dbt;
dbt = t & VT_BTYPE;
/* XXX: add optimization if lvalue : just change type and offset */
if (dbt == VT_BYTE)
bits = 8;
else
bits = 16;
if (t & VT_UNSIGNED) {
vpushi((1 << bits) - 1);
gen_op('&');
} else {
bits = 32 - bits;
vpushi(bits);
gen_op(TOK_SHL);
/* result must be signed or the SAR is converted to an SHL
This was not the case when "t" was a signed short
and the last value on the stack was an unsigned int */
vtop->type.t &= ~VT_UNSIGNED;
vpushi(bits);
gen_op(TOK_SAR);
}
}
/* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
static void gen_cast(CType *type)
{
int sbt, dbt, sf, df, c, p;
/* special delayed cast for char/short */
/* XXX: in some cases (multiple cascaded casts), it may still
be incorrect */
if (vtop->r & VT_MUSTCAST) {
vtop->r &= ~VT_MUSTCAST;
force_charshort_cast(vtop->type.t);
}
/* bitfields first get cast to ints */
if (vtop->type.t & VT_BITFIELD) {
gv(RC_INT);
}
dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
if (sbt != dbt) {
sf = is_float(sbt);
df = is_float(dbt);
c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
if (c) {
/* constant case: we can do it now */
/* XXX: in ISOC, cannot do it if error in convert */
if (sbt == VT_FLOAT)
vtop->c.ld = vtop->c.f;
else if (sbt == VT_DOUBLE)
vtop->c.ld = vtop->c.d;
if (df) {
if ((sbt & VT_BTYPE) == VT_LLONG) {
if (sbt & VT_UNSIGNED)
vtop->c.ld = vtop->c.ull;
else
vtop->c.ld = vtop->c.ll;
} else if(!sf) {
if (sbt & VT_UNSIGNED)
vtop->c.ld = vtop->c.ui;
else
vtop->c.ld = vtop->c.i;
}
if (dbt == VT_FLOAT)
vtop->c.f = (float)vtop->c.ld;
else if (dbt == VT_DOUBLE)
vtop->c.d = (double)vtop->c.ld;
} else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
vtop->c.ull = (unsigned long long)vtop->c.ld;
} else if (sf && dbt == VT_BOOL) {
vtop->c.i = (vtop->c.ld != 0);
} else {
if(sf)
vtop->c.ll = (long long)vtop->c.ld;
else if (sbt == (VT_LLONG|VT_UNSIGNED))
vtop->c.ll = vtop->c.ull;
else if (sbt & VT_UNSIGNED)
vtop->c.ll = vtop->c.ui;
else if (sbt != VT_LLONG)
vtop->c.ll = vtop->c.i;
if (dbt == (VT_LLONG|VT_UNSIGNED))
vtop->c.ull = vtop->c.ll;
else if (dbt == VT_BOOL)
vtop->c.i = (vtop->c.ll != 0);
else if (dbt != VT_LLONG) {
int s = 0;
if ((dbt & VT_BTYPE) == VT_BYTE)
s = 24;
else if ((dbt & VT_BTYPE) == VT_SHORT)
s = 16;
if(dbt & VT_UNSIGNED)
vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
else
vtop->c.i = ((int)vtop->c.ll << s) >> s;
}
}
} else if (p && dbt == VT_BOOL) {
vtop->r = VT_CONST;
vtop->c.i = 1;
} else if (!nocode_wanted) {
/* non constant case: generate code */
if (sf && df) {
/* convert from fp to fp */
gen_cvt_ftof(dbt);
} else if (df) {
/* convert int to fp */
gen_cvt_itof1(dbt);
} else if (sf) {
/* convert fp to int */
if (dbt == VT_BOOL) {
vpushi(0);
gen_op(TOK_NE);
} else {
/* we handle char/short/etc... with generic code */
if (dbt != (VT_INT | VT_UNSIGNED) &&
dbt != (VT_LLONG | VT_UNSIGNED) &&
dbt != VT_LLONG)
dbt = VT_INT;
gen_cvt_ftoi1(dbt);
if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
/* additional cast for char/short... */
vtop->type.t = dbt;
gen_cast(type);
}
}
#ifndef TCC_TARGET_X86_64
} else if ((dbt & VT_BTYPE) == VT_LLONG) {
if ((sbt & VT_BTYPE) != VT_LLONG) {
/* scalar to long long */
/* machine independent conversion */
gv(RC_INT);
/* generate high word */
if (sbt == (VT_INT | VT_UNSIGNED)) {
vpushi(0);
gv(RC_INT);
} else {
if (sbt == VT_PTR) {
/* cast from pointer to int before we apply
shift operation, which pointers don't support*/
gen_cast(&int_type);
}
gv_dup();
vpushi(31);
gen_op(TOK_SAR);
}
/* patch second register */
vtop[-1].r2 = vtop->r;
vpop();
}
#else
} else if ((dbt & VT_BTYPE) == VT_LLONG ||
(dbt & VT_BTYPE) == VT_PTR) {
/* XXX: not sure if this is perfect... need more tests */
if ((sbt & VT_BTYPE) != VT_LLONG) {
int r = gv(RC_INT);
if (sbt != (VT_INT | VT_UNSIGNED) &&
sbt != VT_PTR && sbt != VT_FUNC) {
/* x86_64 specific: movslq */
o(0x6348);
o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
}
}
#endif
} else if (dbt == VT_BOOL) {
/* scalar to bool */
vpushi(0);
gen_op(TOK_NE);
} else if ((dbt & VT_BTYPE) == VT_BYTE ||
(dbt & VT_BTYPE) == VT_SHORT) {
if (sbt == VT_PTR) {
vtop->type.t = VT_INT;
warning("nonportable conversion from pointer to char/short");
}
force_charshort_cast(dbt);
} else if ((dbt & VT_BTYPE) == VT_INT) {
/* scalar to int */
if (sbt == VT_LLONG) {
/* from long long: just take low order word */
lexpand();
vpop();
}
/* if lvalue and single word type, nothing to do because
the lvalue already contains the real type size (see
VT_LVAL_xxx constants) */
}
}
} else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
/* if we are casting between pointer types,
we must update the VT_LVAL_xxx size */
vtop->r = (vtop->r & ~VT_LVAL_TYPE)
| (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
}
vtop->type = *type;
}
/* return type size. Put alignment at 'a' */
static int type_size(CType *type, int *a)
{
Sym *s;
int bt;
bt = type->t & VT_BTYPE;
if (bt == VT_STRUCT) {
/* struct/union */
s = type->ref;
*a = s->r;
return s->c;
} else if (bt == VT_PTR) {
if (type->t & VT_ARRAY) {
int ts;
s = type->ref;
ts = type_size(&s->type, a);
if (ts < 0 && s->c < 0)
ts = -ts;
return ts * s->c;
} else {
*a = PTR_SIZE;
return PTR_SIZE;
}
} else if (bt == VT_LDOUBLE) {
*a = LDOUBLE_ALIGN;
return LDOUBLE_SIZE;
} else if (bt == VT_DOUBLE || bt == VT_LLONG) {
#ifdef TCC_TARGET_I386
#ifdef TCC_TARGET_PE
*a = 8;
#else
*a = 4;
#endif
#elif defined(TCC_TARGET_ARM)
#ifdef TCC_ARM_EABI
*a = 8;
#else
*a = 4;
#endif
#else
*a = 8;
#endif
return 8;
} else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
*a = 4;
return 4;
} else if (bt == VT_SHORT) {
*a = 2;
return 2;
} else {
/* char, void, function, _Bool */
*a = 1;
return 1;
}
}
/* return the pointed type of t */
static inline CType *pointed_type(CType *type)
{
return &type->ref->type;
}
/* modify type so that its it is a pointer to type. */
static void mk_pointer(CType *type)
{
Sym *s;
s = sym_push(SYM_FIELD, type, 0, -1);
type->t = VT_PTR | (type->t & ~VT_TYPE);
type->ref = s;
}
/* compare function types. OLD functions match any new functions */
static int is_compatible_func(CType *type1, CType *type2)
{
Sym *s1, *s2;
s1 = type1->ref;
s2 = type2->ref;
if (!is_compatible_types(&s1->type, &s2->type))
return 0;
/* check func_call */
if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
return 0;
/* XXX: not complete */
if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
return 1;
if (s1->c != s2->c)
return 0;
while (s1 != NULL) {
if (s2 == NULL)
return 0;
if (!is_compatible_parameter_types(&s1->type, &s2->type))
return 0;
s1 = s1->next;
s2 = s2->next;
}
if (s2)
return 0;
return 1;
}
/* return true if type1 and type2 are the same. If unqualified is
true, qualifiers on the types are ignored.
- enums are not checked as gcc __builtin_types_compatible_p ()
*/
static int compare_types(CType *type1, CType *type2, int unqualified)
{
int bt1, t1, t2;
t1 = type1->t & VT_TYPE;
t2 = type2->t & VT_TYPE;
if (unqualified) {
/* strip qualifiers before comparing */
t1 &= ~(VT_CONSTANT | VT_VOLATILE);
t2 &= ~(VT_CONSTANT | VT_VOLATILE);
}
/* XXX: bitfields ? */
if (t1 != t2)
return 0;
/* test more complicated cases */
bt1 = t1 & VT_BTYPE;
if (bt1 == VT_PTR) {
type1 = pointed_type(type1);
type2 = pointed_type(type2);
return is_compatible_types(type1, type2);
} else if (bt1 == VT_STRUCT) {
return (type1->ref == type2->ref);
} else if (bt1 == VT_FUNC) {
return is_compatible_func(type1, type2);
} else {
return 1;
}
}
/* return true if type1 and type2 are exactly the same (including
qualifiers).
*/
static int is_compatible_types(CType *type1, CType *type2)
{
return compare_types(type1,type2,0);
}
/* return true if type1 and type2 are the same (ignoring qualifiers).
*/
static int is_compatible_parameter_types(CType *type1, CType *type2)
{
return compare_types(type1,type2,1);
}
/* print a type. If 'varstr' is not NULL, then the variable is also
printed in the type */
/* XXX: union */
/* XXX: add array and function pointers */
void type_to_str(char *buf, int buf_size,
CType *type, const char *varstr)
{
int bt, v, t;
Sym *s, *sa;
char buf1[256];
const char *tstr;
t = type->t & VT_TYPE;
bt = t & VT_BTYPE;
buf[0] = '\0';
if (t & VT_CONSTANT)
pstrcat(buf, buf_size, "const ");
if (t & VT_VOLATILE)
pstrcat(buf, buf_size, "volatile ");
if (t & VT_UNSIGNED)
pstrcat(buf, buf_size, "unsigned ");
switch(bt) {
case VT_VOID:
tstr = "void";
goto add_tstr;
case VT_BOOL:
tstr = "_Bool";
goto add_tstr;
case VT_BYTE:
tstr = "char";
goto add_tstr;
case VT_SHORT:
tstr = "short";
goto add_tstr;
case VT_INT:
tstr = "int";
goto add_tstr;
case VT_LONG:
tstr = "long";
goto add_tstr;
case VT_LLONG:
tstr = "long long";
goto add_tstr;
case VT_FLOAT:
tstr = "float";
goto add_tstr;
case VT_DOUBLE:
tstr = "double";
goto add_tstr;
case VT_LDOUBLE:
tstr = "long double";
add_tstr:
pstrcat(buf, buf_size, tstr);
break;
case VT_ENUM:
case VT_STRUCT:
if (bt == VT_STRUCT)
tstr = "struct ";
else
tstr = "enum ";
pstrcat(buf, buf_size, tstr);
v = type->ref->v & ~SYM_STRUCT;
if (v >= SYM_FIRST_ANOM)
pstrcat(buf, buf_size, "<anonymous>");
else
pstrcat(buf, buf_size, get_tok_str(v, NULL));
break;
case VT_FUNC:
s = type->ref;
type_to_str(buf, buf_size, &s->type, varstr);
pstrcat(buf, buf_size, "(");
sa = s->next;
while (sa != NULL) {
type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
pstrcat(buf, buf_size, buf1);
sa = sa->next;
if (sa)
pstrcat(buf, buf_size, ", ");
}
pstrcat(buf, buf_size, ")");
goto no_var;
case VT_PTR:
s = type->ref;
pstrcpy(buf1, sizeof(buf1), "*");
if (varstr)
pstrcat(buf1, sizeof(buf1), varstr);
type_to_str(buf, buf_size, &s->type, buf1);
goto no_var;
}
if (varstr) {
pstrcat(buf, buf_size, " ");
pstrcat(buf, buf_size, varstr);
}
no_var: ;
}
/* verify type compatibility to store vtop in 'dt' type, and generate
casts if needed. */
static void gen_assign_cast(CType *dt)
{
CType *st, *type1, *type2, tmp_type1, tmp_type2;
char buf1[256], buf2[256];
int dbt, sbt;
st = &vtop->type; /* source type */
dbt = dt->t & VT_BTYPE;
sbt = st->t & VT_BTYPE;
if (dt->t & VT_CONSTANT)
warning("assignment of read-only location");
switch(dbt) {
case VT_PTR:
/* special cases for pointers */
/* '0' can also be a pointer */
if (is_null_pointer(vtop))
goto type_ok;
/* accept implicit pointer to integer cast with warning */
if (is_integer_btype(sbt)) {
warning("assignment makes pointer from integer without a cast");
goto type_ok;
}
type1 = pointed_type(dt);
/* a function is implicitely a function pointer */
if (sbt == VT_FUNC) {
if ((type1->t & VT_BTYPE) != VT_VOID &&
!is_compatible_types(pointed_type(dt), st))
goto error;
else
goto type_ok;
}
if (sbt != VT_PTR)
goto error;
type2 = pointed_type(st);
if ((type1->t & VT_BTYPE) == VT_VOID ||
(type2->t & VT_BTYPE) == VT_VOID) {
/* void * can match anything */
} else {
/* exact type match, except for unsigned */
tmp_type1 = *type1;
tmp_type2 = *type2;
tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
if (!is_compatible_types(&tmp_type1, &tmp_type2))
warning("assignment from incompatible pointer type");
}
/* check const and volatile */
if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
(!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
warning("assignment discards qualifiers from pointer target type");
break;
case VT_BYTE:
case VT_SHORT:
case VT_INT:
case VT_LLONG:
if (sbt == VT_PTR || sbt == VT_FUNC) {
warning("assignment makes integer from pointer without a cast");
}
/* XXX: more tests */
break;
case VT_STRUCT:
tmp_type1 = *dt;
tmp_type2 = *st;
tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
error:
type_to_str(buf1, sizeof(buf1), st, NULL);
type_to_str(buf2, sizeof(buf2), dt, NULL);
error("cannot cast '%s' to '%s'", buf1, buf2);
}
break;
}
type_ok:
gen_cast(dt);
}
/* store vtop in lvalue pushed on stack */
void vstore(void)
{
int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
ft = vtop[-1].type.t;
sbt = vtop->type.t & VT_BTYPE;
dbt = ft & VT_BTYPE;
if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
(sbt == VT_INT && dbt == VT_SHORT)) {
/* optimize char/short casts */
delayed_cast = VT_MUSTCAST;
vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
/* XXX: factorize */
if (ft & VT_CONSTANT)
warning("assignment of read-only location");
} else {
delayed_cast = 0;
if (!(ft & VT_BITFIELD))
gen_assign_cast(&vtop[-1].type);
}
if (sbt == VT_STRUCT) {
/* if structure, only generate pointer */
/* structure assignment : generate memcpy */
/* XXX: optimize if small size */
if (!nocode_wanted) {
size = type_size(&vtop->type, &align);
#ifdef TCC_ARM_EABI
if(!(align & 7))
vpush_global_sym(&func_old_type, TOK_memcpy8);
else if(!(align & 3))
vpush_global_sym(&func_old_type, TOK_memcpy4);
else
#endif
vpush_global_sym(&func_old_type, TOK_memcpy);
/* destination */
vpushv(vtop - 2);
vtop->type.t = VT_PTR;
gaddrof();
/* source */
vpushv(vtop - 2);
vtop->type.t = VT_PTR;
gaddrof();
/* type size */
vpushi(size);
gfunc_call(3);
vswap();
vpop();
} else {
vswap();
vpop();
}
/* leave source on stack */
} else if (ft & VT_BITFIELD) {
/* bitfield store handling */
bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
/* remove bit field info to avoid loops */
vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
/* duplicate source into other register */
gv_dup();
vswap();
vrott(3);
if((ft & VT_BTYPE) == VT_BOOL) {
gen_cast(&vtop[-1].type);
vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
}
/* duplicate destination */
vdup();
vtop[-1] = vtop[-2];
/* mask and shift source */
if((ft & VT_BTYPE) != VT_BOOL) {
if((ft & VT_BTYPE) == VT_LLONG) {
vpushll((1ULL << bit_size) - 1ULL);
} else {
vpushi((1 << bit_size) - 1);
}
gen_op('&');
}
vpushi(bit_pos);
gen_op(TOK_SHL);
/* load destination, mask and or with source */
vswap();
if((ft & VT_BTYPE) == VT_LLONG) {
vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
} else {
vpushi(~(((1 << bit_size) - 1) << bit_pos));
}
gen_op('&');
gen_op('|');
/* store result */
vstore();
/* pop off shifted source from "duplicate source..." above */
vpop();
} else {
#ifdef CONFIG_TCC_BCHECK
/* bound check case */
if (vtop[-1].r & VT_MUSTBOUND) {
vswap();
gbound();
vswap();
}
#endif
if (!nocode_wanted) {
rc = RC_INT;
if (is_float(ft)) {
rc = RC_FLOAT;
#ifdef TCC_TARGET_X86_64
if ((ft & VT_BTYPE) == VT_LDOUBLE) {
rc = RC_ST0;
}
#endif
}
r = gv(rc); /* generate value */
/* if lvalue was saved on stack, must read it */
if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
SValue sv;
t = get_reg(RC_INT);
#ifdef TCC_TARGET_X86_64
sv.type.t = VT_PTR;
#else
sv.type.t = VT_INT;
#endif
sv.r = VT_LOCAL | VT_LVAL;
sv.c.ul = vtop[-1].c.ul;
load(t, &sv);
vtop[-1].r = t | VT_LVAL;
}
store(r, vtop - 1);
#ifndef TCC_TARGET_X86_64
/* two word case handling : store second register at word + 4 */
if ((ft & VT_BTYPE) == VT_LLONG) {
vswap();
/* convert to int to increment easily */
vtop->type.t = VT_INT;
gaddrof();
vpushi(4);
gen_op('+');
vtop->r |= VT_LVAL;
vswap();
/* XXX: it works because r2 is spilled last ! */
store(vtop->r2, vtop - 1);
}
#endif
}
vswap();
vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
vtop->r |= delayed_cast;
}
}
/* post defines POST/PRE add. c is the token ++ or -- */
void inc(int post, int c)
{
test_lvalue();
vdup(); /* save lvalue */
if (post) {
gv_dup(); /* duplicate value */
vrotb(3);
vrotb(3);
}
/* add constant */
vpushi(c - TOK_MID);
gen_op('+');
vstore(); /* store value */
if (post)
vpop(); /* if post op, return saved value */
}
/* Parse GNUC __attribute__ extension. Currently, the following
extensions are recognized:
- aligned(n) : set data/function alignment.
- packed : force data alignment to 1
- section(x) : generate data/code in this section.
- unused : currently ignored, but may be used someday.
- regparm(n) : pass function parameters in registers (i386 only)
*/
static void parse_attribute(AttributeDef *ad)
{
int t, n;
while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
next();
skip('(');
skip('(');
while (tok != ')') {
if (tok < TOK_IDENT)
expect("attribute name");
t = tok;
next();
switch(t) {
case TOK_SECTION1:
case TOK_SECTION2:
skip('(');
if (tok != TOK_STR)
expect("section name");
ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
next();
skip(')');
break;
case TOK_ALIGNED1:
case TOK_ALIGNED2:
if (tok == '(') {
next();
n = expr_const();
if (n <= 0 || (n & (n - 1)) != 0)
error("alignment must be a positive power of two");
skip(')');
} else {
n = MAX_ALIGN;
}
ad->aligned = n;
break;
case TOK_PACKED1:
case TOK_PACKED2:
ad->packed = 1;
break;
case TOK_UNUSED1:
case TOK_UNUSED2:
/* currently, no need to handle it because tcc does not
track unused objects */
break;
case TOK_NORETURN1:
case TOK_NORETURN2:
/* currently, no need to handle it because tcc does not
track unused objects */
break;
case TOK_CDECL1:
case TOK_CDECL2:
case TOK_CDECL3:
FUNC_CALL(ad->func_attr) = FUNC_CDECL;
break;
case TOK_STDCALL1:
case TOK_STDCALL2:
case TOK_STDCALL3:
FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
break;
#ifdef TCC_TARGET_I386
case TOK_REGPARM1:
case TOK_REGPARM2:
skip('(');
n = expr_const();
if (n > 3)
n = 3;
else if (n < 0)
n = 0;
if (n > 0)
FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
skip(')');
break;
case TOK_FASTCALL1:
case TOK_FASTCALL2:
case TOK_FASTCALL3:
FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
break;
#endif
case TOK_DLLEXPORT:
FUNC_EXPORT(ad->func_attr) = 1;
break;
default:
if (tcc_state->warn_unsupported)
warning("'%s' attribute ignored", get_tok_str(t, NULL));
/* skip parameters */
if (tok == '(') {
int parenthesis = 0;
do {
if (tok == '(')
parenthesis++;
else if (tok == ')')
parenthesis--;
next();
} while (parenthesis && tok != -1);
}
break;
}
if (tok != ',')
break;
next();
}
skip(')');
skip(')');
}
}
/* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
static void struct_decl(CType *type, int u)
{
int a, v, size, align, maxalign, c, offset;
int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
Sym *s, *ss, *ass, **ps;
AttributeDef ad;
CType type1, btype;
a = tok; /* save decl type */
next();
if (tok != '{') {
v = tok;
next();
/* struct already defined ? return it */
if (v < TOK_IDENT)
expect("struct/union/enum name");
s = struct_find(v);
if (s) {
if (s->type.t != a)
error("invalid type");
goto do_decl;
}
} else {
v = anon_sym++;
}
type1.t = a;
/* we put an undefined size for struct/union */
s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
s->r = 0; /* default alignment is zero as gcc */
/* put struct/union/enum name in type */
do_decl:
type->t = u;
type->ref = s;
if (tok == '{') {
next();
if (s->c != -1)
error("struct/union/enum already defined");
/* cannot be empty */
c = 0;
/* non empty enums are not allowed */
if (a == TOK_ENUM) {
for(;;) {
v = tok;
if (v < TOK_UIDENT)
expect("identifier");
next();
if (tok == '=') {
next();
c = expr_const();
}
/* enum symbols have static storage */
ss = sym_push(v, &int_type, VT_CONST, c);
ss->type.t |= VT_STATIC;
if (tok != ',')
break;
next();
c++;
/* NOTE: we accept a trailing comma */
if (tok == '}')
break;
}
skip('}');
} else {
maxalign = 1;
ps = &s->next;
prevbt = VT_INT;
bit_pos = 0;
offset = 0;
while (tok != '}') {
parse_btype(&btype, &ad);
while (1) {
bit_size = -1;
v = 0;
type1 = btype;
if (tok != ':') {
type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
expect("identifier");
if ((type1.t & VT_BTYPE) == VT_FUNC ||
(type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
error("invalid type for '%s'",
get_tok_str(v, NULL));
}
if (tok == ':') {
next();
bit_size = expr_const();
/* XXX: handle v = 0 case for messages */
if (bit_size < 0)
error("negative width in bit-field '%s'",
get_tok_str(v, NULL));
if (v && bit_size == 0)
error("zero width for bit-field '%s'",
get_tok_str(v, NULL));
}
size = type_size(&type1, &align);
if (ad.aligned) {
if (align < ad.aligned)
align = ad.aligned;
} else if (ad.packed) {
align = 1;
} else if (*tcc_state->pack_stack_ptr) {
if (align > *tcc_state->pack_stack_ptr)
align = *tcc_state->pack_stack_ptr;
}
lbit_pos = 0;
if (bit_size >= 0) {
bt = type1.t & VT_BTYPE;
if (bt != VT_INT &&
bt != VT_BYTE &&
bt != VT_SHORT &&
bt != VT_BOOL &&
bt != VT_ENUM &&
bt != VT_LLONG)
error("bitfields must have scalar type");
bsize = size * 8;
if (bit_size > bsize) {
error("width of '%s' exceeds its type",
get_tok_str(v, NULL));
} else if (bit_size == bsize) {
/* no need for bit fields */
bit_pos = 0;
} else if (bit_size == 0) {
/* XXX: what to do if only padding in a
structure ? */
/* zero size: means to pad */
bit_pos = 0;
} else {
/* we do not have enough room ?
did the type change?
is it a union? */
if ((bit_pos + bit_size) > bsize ||
bt != prevbt || a == TOK_UNION)
bit_pos = 0;
lbit_pos = bit_pos;
/* XXX: handle LSB first */
type1.t |= VT_BITFIELD |
(bit_pos << VT_STRUCT_SHIFT) |
(bit_size << (VT_STRUCT_SHIFT + 6));
bit_pos += bit_size;
}
prevbt = bt;
} else {
bit_pos = 0;
}
if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
/* add new memory data only if starting
bit field */
if (lbit_pos == 0) {
if (a == TOK_STRUCT) {
c = (c + align - 1) & -align;
offset = c;
if (size > 0)
c += size;
} else {
offset = 0;
if (size > c)
c = size;
}
if (align > maxalign)
maxalign = align;
}
#if 0
printf("add field %s offset=%d",
get_tok_str(v, NULL), offset);
if (type1.t & VT_BITFIELD) {
printf(" pos=%d size=%d",
(type1.t >> VT_STRUCT_SHIFT) & 0x3f,
(type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
}
printf("\n");
#endif
}
if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
ass = type1.ref;
while ((ass = ass->next) != NULL) {
ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
*ps = ss;
ps = &ss->next;
}
} else if (v) {
ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
*ps = ss;
ps = &ss->next;
}
if (tok == ';' || tok == TOK_EOF)
break;
skip(',');
}
skip(';');
}
skip('}');
/* store size and alignment */
s->c = (c + maxalign - 1) & -maxalign;
s->r = maxalign;
}
}
}
/* return 0 if no type declaration. otherwise, return the basic type
and skip it.
*/
static int parse_btype(CType *type, AttributeDef *ad)
{
int t, u, type_found, typespec_found, typedef_found;
Sym *s;
CType type1;
memset(ad, 0, sizeof(AttributeDef));
type_found = 0;
typespec_found = 0;
typedef_found = 0;
t = 0;
while(1) {
switch(tok) {
case TOK_EXTENSION:
/* currently, we really ignore extension */
next();
continue;
/* basic types */
case TOK_CHAR:
u = VT_BYTE;
basic_type:
next();
basic_type1:
if ((t & VT_BTYPE) != 0)
error("too many basic types");
t |= u;
typespec_found = 1;
break;
case TOK_VOID:
u = VT_VOID;
goto basic_type;
case TOK_SHORT:
u = VT_SHORT;
goto basic_type;
case TOK_INT:
next();
typespec_found = 1;
break;
case TOK_LONG:
next();
if ((t & VT_BTYPE) == VT_DOUBLE) {
t = (t & ~VT_BTYPE) | VT_LDOUBLE;
} else if ((t & VT_BTYPE) == VT_LONG) {
t = (t & ~VT_BTYPE) | VT_LLONG;
} else {
u = VT_LONG;
goto basic_type1;
}
break;
case TOK_BOOL:
u = VT_BOOL;
goto basic_type;
case TOK_FLOAT:
u = VT_FLOAT;
goto basic_type;
case TOK_DOUBLE:
next();
if ((t & VT_BTYPE) == VT_LONG) {
t = (t & ~VT_BTYPE) | VT_LDOUBLE;
} else {
u = VT_DOUBLE;
goto basic_type1;
}
break;
case TOK_ENUM:
struct_decl(&type1, VT_ENUM);
basic_type2:
u = type1.t;
type->ref = type1.ref;
goto basic_type1;
case TOK_STRUCT:
case TOK_UNION:
struct_decl(&type1, VT_STRUCT);
goto basic_type2;
/* type modifiers */
case TOK_CONST1:
case TOK_CONST2:
case TOK_CONST3:
t |= VT_CONSTANT;
next();
break;
case TOK_VOLATILE1:
case TOK_VOLATILE2:
case TOK_VOLATILE3:
t |= VT_VOLATILE;
next();
break;
case TOK_SIGNED1:
case TOK_SIGNED2:
case TOK_SIGNED3:
typespec_found = 1;
t |= VT_SIGNED;
next();
break;
case TOK_REGISTER:
case TOK_AUTO:
case TOK_RESTRICT1:
case TOK_RESTRICT2:
case TOK_RESTRICT3:
next();
break;
case TOK_UNSIGNED:
t |= VT_UNSIGNED;
next();
typespec_found = 1;
break;
/* storage */
case TOK_EXTERN:
t |= VT_EXTERN;
next();
break;
case TOK_STATIC:
t |= VT_STATIC;
next();
break;
case TOK_TYPEDEF:
t |= VT_TYPEDEF;
next();
break;
case TOK_INLINE1:
case TOK_INLINE2:
case TOK_INLINE3:
t |= VT_INLINE;
next();
break;
/* GNUC attribute */
case TOK_ATTRIBUTE1:
case TOK_ATTRIBUTE2:
parse_attribute(ad);
break;
/* GNUC typeof */
case TOK_TYPEOF1:
case TOK_TYPEOF2:
case TOK_TYPEOF3:
next();
parse_expr_type(&type1);
goto basic_type2;
default:
if (typespec_found || typedef_found)
goto the_end;
s = sym_find(tok);
if (!s || !(s->type.t & VT_TYPEDEF))
goto the_end;
typedef_found = 1;
t |= (s->type.t & ~VT_TYPEDEF);
type->ref = s->type.ref;
next();
typespec_found = 1;
break;
}
type_found = 1;
}
the_end:
if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
error("signed and unsigned modifier");
if (tcc_state->char_is_unsigned) {
if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
t |= VT_UNSIGNED;
}
t &= ~VT_SIGNED;
/* long is never used as type */
if ((t & VT_BTYPE) == VT_LONG)
#ifndef TCC_TARGET_X86_64
t = (t & ~VT_BTYPE) | VT_INT;
#else
t = (t & ~VT_BTYPE) | VT_LLONG;
#endif
type->t = t;
return type_found;
}
/* convert a function parameter type (array to pointer and function to
function pointer) */
static inline void convert_parameter_type(CType *pt)
{
/* remove const and volatile qualifiers (XXX: const could be used
to indicate a const function parameter */
pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
/* array must be transformed to pointer according to ANSI C */
pt->t &= ~VT_ARRAY;
if ((pt->t & VT_BTYPE) == VT_FUNC) {
mk_pointer(pt);
}
}
static void post_type(CType *type, AttributeDef *ad)
{
int n, l, t1, arg_size, align;
Sym **plast, *s, *first;
AttributeDef ad1;
CType pt;
if (tok == '(') {
/* function declaration */
next();
l = 0;
first = NULL;
plast = &first;
arg_size = 0;
if (tok != ')') {
for(;;) {
/* read param name and compute offset */
if (l != FUNC_OLD) {
if (!parse_btype(&pt, &ad1)) {
if (l) {
error("invalid type");
} else {
l = FUNC_OLD;
goto old_proto;
}
}
l = FUNC_NEW;
if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
break;
type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
if ((pt.t & VT_BTYPE) == VT_VOID)
error("parameter declared as void");
arg_size += (type_size(&pt, &align) + 3) & ~3;
} else {
old_proto:
n = tok;
if (n < TOK_UIDENT)
expect("identifier");
pt.t = VT_INT;
next();
}
convert_parameter_type(&pt);
s = sym_push(n | SYM_FIELD, &pt, 0, 0);
*plast = s;
plast = &s->next;
if (tok == ')')
break;
skip(',');
if (l == FUNC_NEW && tok == TOK_DOTS) {
l = FUNC_ELLIPSIS;
next();
break;
}
}
}
/* if no parameters, then old type prototype */
if (l == 0)
l = FUNC_OLD;
skip(')');
t1 = type->t & VT_STORAGE;
/* NOTE: const is ignored in returned type as it has a special
meaning in gcc / C++ */
type->t &= ~(VT_STORAGE | VT_CONSTANT);
post_type(type, ad);
/* we push a anonymous symbol which will contain the function prototype */
FUNC_ARGS(ad->func_attr) = arg_size;
s = sym_push(SYM_FIELD, type, ad->func_attr, l);
s->next = first;
type->t = t1 | VT_FUNC;
type->ref = s;
} else if (tok == '[') {
/* array definition */
next();
if (tok == TOK_RESTRICT1)
next();
n = -1;
if (tok != ']') {
n = expr_const();
if (n < 0)
error("invalid array size");
}
skip(']');
/* parse next post type */
t1 = type->t & VT_STORAGE;
type->t &= ~VT_STORAGE;
post_type(type, ad);
/* we push a anonymous symbol which will contain the array
element type */
s = sym_push(SYM_FIELD, type, 0, n);
type->t = t1 | VT_ARRAY | VT_PTR;
type->ref = s;
}
}
/* Parse a type declaration (except basic type), and return the type
in 'type'. 'td' is a bitmask indicating which kind of type decl is
expected. 'type' should contain the basic type. 'ad' is the
attribute definition of the basic type. It can be modified by
type_decl().
*/
static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
{
Sym *s;
CType type1, *type2;
int qualifiers;
while (tok == '*') {
qualifiers = 0;
redo:
next();
switch(tok) {
case TOK_CONST1:
case TOK_CONST2:
case TOK_CONST3:
qualifiers |= VT_CONSTANT;
goto redo;
case TOK_VOLATILE1:
case TOK_VOLATILE2:
case TOK_VOLATILE3:
qualifiers |= VT_VOLATILE;
goto redo;
case TOK_RESTRICT1:
case TOK_RESTRICT2:
case TOK_RESTRICT3:
goto redo;
}
mk_pointer(type);
type->t |= qualifiers;
}
/* XXX: clarify attribute handling */
if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
parse_attribute(ad);
/* recursive type */
/* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
type1.t = 0; /* XXX: same as int */
if (tok == '(') {
next();
/* XXX: this is not correct to modify 'ad' at this point, but
the syntax is not clear */
if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
parse_attribute(ad);
type_decl(&type1, ad, v, td);
skip(')');
} else {
/* type identifier */
if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
*v = tok;
next();
} else {
if (!(td & TYPE_ABSTRACT))
expect("identifier");
*v = 0;
}
}
post_type(type, ad);
if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
parse_attribute(ad);
if (!type1.t)
return;
/* append type at the end of type1 */
type2 = &type1;
for(;;) {
s = type2->ref;
type2 = &s->type;
if (!type2->t) {
*type2 = *type;
break;
}
}
*type = type1;
}
/* compute the lvalue VT_LVAL_xxx needed to match type t. */
static int lvalue_type(int t)
{
int bt, r;
r = VT_LVAL;
bt = t & VT_BTYPE;
if (bt == VT_BYTE || bt == VT_BOOL)
r |= VT_LVAL_BYTE;
else if (bt == VT_SHORT)
r |= VT_LVAL_SHORT;
else
return r;
if (t & VT_UNSIGNED)
r |= VT_LVAL_UNSIGNED;
return r;
}
/* indirection with full error checking and bound check */
static void indir(void)
{
if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
return;
expect("pointer");
}
if ((vtop->r & VT_LVAL) && !nocode_wanted)
gv(RC_INT);
vtop->type = *pointed_type(&vtop->type);
/* Arrays and functions are never lvalues */
if (!(vtop->type.t & VT_ARRAY)
&& (vtop->type.t & VT_BTYPE) != VT_FUNC) {
vtop->r |= lvalue_type(vtop->type.t);
/* if bound checking, the referenced pointer must be checked */
if (tcc_state->do_bounds_check)
vtop->r |= VT_MUSTBOUND;
}
}
/* pass a parameter to a function and do type checking and casting */
static void gfunc_param_typed(Sym *func, Sym *arg)
{
int func_type;
CType type;
func_type = func->c;
if (func_type == FUNC_OLD ||
(func_type == FUNC_ELLIPSIS && arg == NULL)) {
/* default casting : only need to convert float to double */
if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
type.t = VT_DOUBLE;
gen_cast(&type);
}
} else if (arg == NULL) {
error("too many arguments to function");
} else {
type = arg->type;
type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
gen_assign_cast(&type);
}
}
/* parse an expression of the form '(type)' or '(expr)' and return its
type */
static void parse_expr_type(CType *type)
{
int n;
AttributeDef ad;
skip('(');
if (parse_btype(type, &ad)) {
type_decl(type, &ad, &n, TYPE_ABSTRACT);
} else {
expr_type(type);
}
skip(')');
}
static void parse_type(CType *type)
{
AttributeDef ad;
int n;
if (!parse_btype(type, &ad)) {
expect("type");
}
type_decl(type, &ad, &n, TYPE_ABSTRACT);
}
static void vpush_tokc(int t)
{
CType type;
type.t = t;
vsetc(&type, VT_CONST, &tokc);
}
static void unary(void)
{
int n, t, align, size, r;
CType type;
Sym *s;
AttributeDef ad;
/* XXX: GCC 2.95.3 does not generate a table although it should be
better here */
tok_next:
switch(tok) {
case TOK_EXTENSION:
next();
goto tok_next;
case TOK_CINT:
case TOK_CCHAR:
case TOK_LCHAR:
vpushi(tokc.i);
next();
break;
case TOK_CUINT:
vpush_tokc(VT_INT | VT_UNSIGNED);
next();
break;
case TOK_CLLONG:
vpush_tokc(VT_LLONG);
next();
break;
case TOK_CULLONG:
vpush_tokc(VT_LLONG | VT_UNSIGNED);
next();
break;
case TOK_CFLOAT:
vpush_tokc(VT_FLOAT);
next();
break;
case TOK_CDOUBLE:
vpush_tokc(VT_DOUBLE);
next();
break;
case TOK_CLDOUBLE:
vpush_tokc(VT_LDOUBLE);
next();
break;
case TOK___FUNCTION__:
if (!gnu_ext)
goto tok_identifier;
/* fall thru */
case TOK___FUNC__:
{
void *ptr;
int len;
/* special function name identifier */
len = strlen(funcname) + 1;
/* generate char[len] type */
type.t = VT_BYTE;
mk_pointer(&type);
type.t |= VT_ARRAY;
type.ref->c = len;
vpush_ref(&type, data_section, data_section->data_offset, len);
ptr = section_ptr_add(data_section, len);
memcpy(ptr, funcname, len);
next();
}
break;
case TOK_LSTR:
#ifdef TCC_TARGET_PE
t = VT_SHORT | VT_UNSIGNED;
#else
t = VT_INT;
#endif
goto str_init;
case TOK_STR:
/* string parsing */
t = VT_BYTE;
str_init:
if (tcc_state->warn_write_strings)
t |= VT_CONSTANT;
type.t = t;
mk_pointer(&type);
type.t |= VT_ARRAY;
memset(&ad, 0, sizeof(AttributeDef));
decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
break;
case '(':
next();
/* cast ? */
if (parse_btype(&type, &ad)) {
type_decl(&type, &ad, &n, TYPE_ABSTRACT);
skip(')');
/* check ISOC99 compound literal */
if (tok == '{') {
/* data is allocated locally by default */
if (global_expr)
r = VT_CONST;
else
r = VT_LOCAL;
/* all except arrays are lvalues */
if (!(type.t & VT_ARRAY))
r |= lvalue_type(type.t);
memset(&ad, 0, sizeof(AttributeDef));
decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
} else {
unary();
gen_cast(&type);
}
} else if (tok == '{') {
/* save all registers */
save_regs(0);
/* statement expression : we do not accept break/continue
inside as GCC does */
block(NULL, NULL, NULL, NULL, 0, 1);
skip(')');
} else {
gexpr();
skip(')');
}
break;
case '*':
next();
unary();
indir();
break;
case '&':
next();
unary();
/* functions names must be treated as function pointers,
except for unary '&' and sizeof. Since we consider that
functions are not lvalues, we only have to handle it
there and in function calls. */
/* arrays can also be used although they are not lvalues */
if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
test_lvalue();
mk_pointer(&vtop->type);
gaddrof();
break;
case '!':
next();
unary();
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
CType boolean;
boolean.t = VT_BOOL;
gen_cast(&boolean);
vtop->c.i = !vtop->c.i;
} else if ((vtop->r & VT_VALMASK) == VT_CMP)
vtop->c.i = vtop->c.i ^ 1;
else {
save_regs(1);
vseti(VT_JMP, gtst(1, 0));
}
break;
case '~':
next();
unary();
vpushi(-1);
gen_op('^');
break;
case '+':
next();
/* in order to force cast, we add zero */
unary();
if ((vtop->type.t & VT_BTYPE) == VT_PTR)
error("pointer not accepted for unary plus");
vpushi(0);
gen_op('+');
break;
case TOK_SIZEOF:
case TOK_ALIGNOF1:
case TOK_ALIGNOF2:
t = tok;
next();
if (tok == '(') {
parse_expr_type(&type);
} else {
unary_type(&type);
}
size = type_size(&type, &align);
if (t == TOK_SIZEOF) {
if (size < 0)
error("sizeof applied to an incomplete type");
vpushi(size);
} else {
vpushi(align);
}
vtop->type.t |= VT_UNSIGNED;
break;
case TOK_builtin_types_compatible_p:
{
CType type1, type2;
next();
skip('(');
parse_type(&type1);
skip(',');
parse_type(&type2);
skip(')');
type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
vpushi(is_compatible_types(&type1, &type2));
}
break;
case TOK_builtin_constant_p:
{
int saved_nocode_wanted, res;
next();
skip('(');
saved_nocode_wanted = nocode_wanted;
nocode_wanted = 1;
gexpr();
res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
vpop();
nocode_wanted = saved_nocode_wanted;
skip(')');
vpushi(res);
}
break;
case TOK_builtin_frame_address:
{
CType type;
next();
skip('(');
if (tok != TOK_CINT) {
error("__builtin_frame_address only takes integers");
}
if (tokc.i != 0) {
error("TCC only supports __builtin_frame_address(0)");
}
next();
skip(')');
type.t = VT_VOID;
mk_pointer(&type);
vset(&type, VT_LOCAL, 0);
}
break;
#ifdef TCC_TARGET_X86_64
case TOK_builtin_malloc:
tok = TOK_malloc;
goto tok_identifier;
case TOK_builtin_free:
tok = TOK_free;
goto tok_identifier;
#endif
case TOK_INC:
case TOK_DEC:
t = tok;
next();
unary();
inc(0, t);
break;
case '-':
next();
vpushi(0);
unary();
gen_op('-');
break;
case TOK_LAND:
if (!gnu_ext)
goto tok_identifier;
next();
/* allow to take the address of a label */
if (tok < TOK_UIDENT)
expect("label identifier");
s = label_find(tok);
if (!s) {
s = label_push(&global_label_stack, tok, LABEL_FORWARD);
} else {
if (s->r == LABEL_DECLARED)
s->r = LABEL_FORWARD;
}
if (!s->type.t) {
s->type.t = VT_VOID;
mk_pointer(&s->type);
s->type.t |= VT_STATIC;
}
vset(&s->type, VT_CONST | VT_SYM, 0);
vtop->sym = s;
next();
break;
default:
tok_identifier:
t = tok;
next();
if (t < TOK_UIDENT)
expect("identifier");
s = sym_find(t);
if (!s) {
if (tok != '(')
error("'%s' undeclared", get_tok_str(t, NULL));
/* for simple function calls, we tolerate undeclared
external reference to int() function */
if (tcc_state->warn_implicit_function_declaration)
warning("implicit declaration of function '%s'",
get_tok_str(t, NULL));
s = external_global_sym(t, &func_old_type, 0);
}
if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
(VT_STATIC | VT_INLINE | VT_FUNC)) {
/* if referencing an inline function, then we generate a
symbol to it if not already done. It will have the
effect to generate code for it at the end of the
compilation unit. Inline function as always
generated in the text section. */
if (!s->c)
put_extern_sym(s, text_section, 0, 0);
r = VT_SYM | VT_CONST;
} else {
r = s->r;
}
vset(&s->type, r, s->c);
/* if forward reference, we must point to s */
if (vtop->r & VT_SYM) {
vtop->sym = s;
vtop->c.ul = 0;
}
break;
}
/* post operations */
while (1) {
if (tok == TOK_INC || tok == TOK_DEC) {
inc(1, tok);
next();
} else if (tok == '.' || tok == TOK_ARROW) {
/* field */
if (tok == TOK_ARROW)
indir();
test_lvalue();
gaddrof();
next();
/* expect pointer on structure */
if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
expect("struct or union");
s = vtop->type.ref;
/* find field */
tok |= SYM_FIELD;
while ((s = s->next) != NULL) {
if (s->v == tok)
break;
}
if (!s)
error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
/* add field offset to pointer */
vtop->type = char_pointer_type; /* change type to 'char *' */
vpushi(s->c);
gen_op('+');
/* change type to field type, and set to lvalue */
vtop->type = s->type;
/* an array is never an lvalue */
if (!(vtop->type.t & VT_ARRAY)) {
vtop->r |= lvalue_type(vtop->type.t);
/* if bound checking, the referenced pointer must be checked */
if (tcc_state->do_bounds_check)
vtop->r |= VT_MUSTBOUND;
}
next();
} else if (tok == '[') {
next();
gexpr();
gen_op('+');
indir();
skip(']');
} else if (tok == '(') {
SValue ret;
Sym *sa;
int nb_args;
/* function call */
if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
/* pointer test (no array accepted) */
if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
vtop->type = *pointed_type(&vtop->type);
if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
goto error_func;
} else {
error_func:
expect("function pointer");
}
} else {
vtop->r &= ~VT_LVAL; /* no lvalue */
}
/* get return type */
s = vtop->type.ref;
next();
sa = s->next; /* first parameter */
nb_args = 0;
ret.r2 = VT_CONST;
/* compute first implicit argument if a structure is returned */
if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
/* get some space for the returned structure */
size = type_size(&s->type, &align);
loc = (loc - size) & -align;
ret.type = s->type;
ret.r = VT_LOCAL | VT_LVAL;
/* pass it as 'int' to avoid structure arg passing
problems */
vseti(VT_LOCAL, loc);
ret.c = vtop->c;
nb_args++;
} else {
ret.type = s->type;
/* return in register */
if (is_float(ret.type.t)) {
ret.r = reg_fret(ret.type.t);
} else {
if ((ret.type.t & VT_BTYPE) == VT_LLONG)
ret.r2 = REG_LRET;
ret.r = REG_IRET;
}
ret.c.i = 0;
}
if (tok != ')') {
for(;;) {
expr_eq();
gfunc_param_typed(s, sa);
nb_args++;
if (sa)
sa = sa->next;
if (tok == ')')
break;
skip(',');
}
}
if (sa)
error("too few arguments to function");
skip(')');
if (!nocode_wanted) {
gfunc_call(nb_args);
} else {
vtop -= (nb_args + 1);
}
/* return value */
vsetc(&ret.type, ret.r, &ret.c);
vtop->r2 = ret.r2;
} else {
break;
}
}
}
static void uneq(void)
{
int t;
unary();
if (tok == '=' ||
(tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
tok == TOK_A_XOR || tok == TOK_A_OR ||
tok == TOK_A_SHL || tok == TOK_A_SAR) {
test_lvalue();
t = tok;
next();
if (t == '=') {
expr_eq();
} else {
vdup();
expr_eq();
gen_op(t & 0x7f);
}
vstore();
}
}
static void expr_prod(void)
{
int t;
uneq();
while (tok == '*' || tok == '/' || tok == '%') {
t = tok;
next();
uneq();
gen_op(t);
}
}
static void expr_sum(void)
{
int t;
expr_prod();
while (tok == '+' || tok == '-') {
t = tok;
next();
expr_prod();
gen_op(t);
}
}
static void expr_shift(void)
{
int t;
expr_sum();
while (tok == TOK_SHL || tok == TOK_SAR) {
t = tok;
next();
expr_sum();
gen_op(t);
}
}
static void expr_cmp(void)
{
int t;
expr_shift();
while ((tok >= TOK_ULE && tok <= TOK_GT) ||
tok == TOK_ULT || tok == TOK_UGE) {
t = tok;
next();
expr_shift();
gen_op(t);
}
}
static void expr_cmpeq(void)
{
int t;
expr_cmp();
while (tok == TOK_EQ || tok == TOK_NE) {
t = tok;
next();
expr_cmp();
gen_op(t);
}
}
static void expr_and(void)
{
expr_cmpeq();
while (tok == '&') {
next();
expr_cmpeq();
gen_op('&');
}
}
static void expr_xor(void)
{
expr_and();
while (tok == '^') {
next();
expr_and();
gen_op('^');
}
}
static void expr_or(void)
{
expr_xor();
while (tok == '|') {
next();
expr_xor();
gen_op('|');
}
}
/* XXX: fix this mess */
static void expr_land_const(void)
{
expr_or();
while (tok == TOK_LAND) {
next();
expr_or();
gen_op(TOK_LAND);
}
}
/* XXX: fix this mess */
static void expr_lor_const(void)
{
expr_land_const();
while (tok == TOK_LOR) {
next();
expr_land_const();
gen_op(TOK_LOR);
}
}
/* only used if non constant */
static void expr_land(void)
{
int t;
expr_or();
if (tok == TOK_LAND) {
t = 0;
save_regs(1);
for(;;) {
t = gtst(1, t);
if (tok != TOK_LAND) {
vseti(VT_JMPI, t);
break;
}
next();
expr_or();
}
}
}
static void expr_lor(void)
{
int t;
expr_land();
if (tok == TOK_LOR) {
t = 0;
save_regs(1);
for(;;) {
t = gtst(0, t);
if (tok != TOK_LOR) {
vseti(VT_JMP, t);
break;
}
next();
expr_land();
}
}
}
/* XXX: better constant handling */
static void expr_eq(void)
{
int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
SValue sv;
CType type, type1, type2;
if (const_wanted) {
expr_lor_const();
if (tok == '?') {
CType boolean;
int c;
boolean.t = VT_BOOL;
vdup();
gen_cast(&boolean);
c = vtop->c.i;
vpop();
next();
if (tok != ':' || !gnu_ext) {
vpop();
gexpr();
}
if (!c)
vpop();
skip(':');
expr_eq();
if (c)
vpop();
}
} else {
expr_lor();
if (tok == '?') {
next();
if (vtop != vstack) {
/* needed to avoid having different registers saved in
each branch */
if (is_float(vtop->type.t)) {
rc = RC_FLOAT;
#ifdef TCC_TARGET_X86_64
if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
rc = RC_ST0;
}
#endif
}
else
rc = RC_INT;
gv(rc);
save_regs(1);
}
if (tok == ':' && gnu_ext) {
gv_dup();
tt = gtst(1, 0);
} else {
tt = gtst(1, 0);
gexpr();
}
type1 = vtop->type;
sv = *vtop; /* save value to handle it later */
vtop--; /* no vpop so that FP stack is not flushed */
skip(':');
u = gjmp(0);
gsym(tt);
expr_eq();
type2 = vtop->type;
t1 = type1.t;
bt1 = t1 & VT_BTYPE;
t2 = type2.t;
bt2 = t2 & VT_BTYPE;
/* cast operands to correct type according to ISOC rules */
if (is_float(bt1) || is_float(bt2)) {
if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
type.t = VT_LDOUBLE;
} else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
type.t = VT_DOUBLE;
} else {
type.t = VT_FLOAT;
}
} else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
/* cast to biggest op */
type.t = VT_LLONG;
/* convert to unsigned if it does not fit in a long long */
if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
(t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
type.t |= VT_UNSIGNED;
} else if (bt1 == VT_PTR || bt2 == VT_PTR) {
/* XXX: test pointer compatibility */
type = type1;
} else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
/* XXX: test function pointer compatibility */
type = type1;
} else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
/* XXX: test structure compatibility */
type = type1;
} else if (bt1 == VT_VOID || bt2 == VT_VOID) {
/* NOTE: as an extension, we accept void on only one side */
type.t = VT_VOID;
} else {
/* integer operations */
type.t = VT_INT;
/* convert to unsigned if it does not fit in an integer */
if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
(t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
type.t |= VT_UNSIGNED;
}
/* now we convert second operand */
gen_cast(&type);
if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
gaddrof();
rc = RC_INT;
if (is_float(type.t)) {
rc = RC_FLOAT;
#ifdef TCC_TARGET_X86_64
if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
rc = RC_ST0;
}
#endif
} else if ((type.t & VT_BTYPE) == VT_LLONG) {
/* for long longs, we use fixed registers to avoid having
to handle a complicated move */
rc = RC_IRET;
}
r2 = gv(rc);
/* this is horrible, but we must also convert first
operand */
tt = gjmp(0);
gsym(u);
/* put again first value and cast it */
*vtop = sv;
gen_cast(&type);
if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
gaddrof();
r1 = gv(rc);
move_reg(r2, r1);
vtop->r = r2;
gsym(tt);
}
}
}
static void gexpr(void)
{
while (1) {
expr_eq();
if (tok != ',')
break;
vpop();
next();
}
}
/* parse an expression and return its type without any side effect. */
static void expr_type(CType *type)
{
int saved_nocode_wanted;
saved_nocode_wanted = nocode_wanted;
nocode_wanted = 1;
gexpr();
*type = vtop->type;
vpop();
nocode_wanted = saved_nocode_wanted;
}
/* parse a unary expression and return its type without any side
effect. */
static void unary_type(CType *type)
{
int a;
a = nocode_wanted;
nocode_wanted = 1;
unary();
*type = vtop->type;
vpop();
nocode_wanted = a;
}
/* parse a constant expression and return value in vtop. */
static void expr_const1(void)
{
int a;
a = const_wanted;
const_wanted = 1;
expr_eq();
const_wanted = a;
}
/* parse an integer constant and return its value. */
static int expr_const(void)
{
int c;
expr_const1();
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
expect("constant expression");
c = vtop->c.i;
vpop();
return c;
}
/* return the label token if current token is a label, otherwise
return zero */
static int is_label(void)
{
int last_tok;
/* fast test first */
if (tok < TOK_UIDENT)
return 0;
/* no need to save tokc because tok is an identifier */
last_tok = tok;
next();
if (tok == ':') {
next();
return last_tok;
} else {
unget_tok(last_tok);
return 0;
}
}
static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
int case_reg, int is_expr)
{
int a, b, c, d;
Sym *s;
/* generate line number info */
if (tcc_state->do_debug &&
(last_line_num != file->line_num || last_ind != ind)) {
put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
last_ind = ind;
last_line_num = file->line_num;
}
if (is_expr) {
/* default return value is (void) */
vpushi(0);
vtop->type.t = VT_VOID;
}
if (tok == TOK_IF) {
/* if test */
next();
skip('(');
gexpr();
skip(')');
a = gtst(1, 0);
block(bsym, csym, case_sym, def_sym, case_reg, 0);
c = tok;
if (c == TOK_ELSE) {
next();
d = gjmp(0);
gsym(a);
block(bsym, csym, case_sym, def_sym, case_reg, 0);
gsym(d); /* patch else jmp */
} else
gsym(a);
} else if (tok == TOK_WHILE) {
next();
d = ind;
skip('(');
gexpr();
skip(')');
a = gtst(1, 0);
b = 0;
block(&a, &b, case_sym, def_sym, case_reg, 0);
gjmp_addr(d);
gsym(a);
gsym_addr(b, d);
} else if (tok == '{') {
Sym *llabel;
next();
/* record local declaration stack position */
s = local_stack;
llabel = local_label_stack;
/* handle local labels declarations */
if (tok == TOK_LABEL) {
next();
for(;;) {
if (tok < TOK_UIDENT)
expect("label identifier");
label_push(&local_label_stack, tok, LABEL_DECLARED);
next();
if (tok == ',') {
next();
} else {
skip(';');
break;
}
}
}
while (tok != '}') {
decl(VT_LOCAL);
if (tok != '}') {
if (is_expr)
vpop();
block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
}
}
/* pop locally defined labels */
label_pop(&local_label_stack, llabel);
/* pop locally defined symbols */
if(is_expr) {
/* XXX: this solution makes only valgrind happy...
triggered by gcc.c-torture/execute/20000917-1.c */
Sym *p;
switch(vtop->type.t & VT_BTYPE) {
case VT_PTR:
case VT_STRUCT:
case VT_ENUM:
case VT_FUNC:
for(p=vtop->type.ref;p;p=p->prev)
if(p->prev==s)
error("unsupported expression type");
}
}
sym_pop(&local_stack, s);
next();
} else if (tok == TOK_RETURN) {
next();
if (tok != ';') {
gexpr();
gen_assign_cast(&func_vt);
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
CType type;
/* if returning structure, must copy it to implicit
first pointer arg location */
#ifdef TCC_ARM_EABI
int align, size;
size = type_size(&func_vt,&align);
if(size <= 4)
{
if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
&& (align & 3))
{
int addr;
loc = (loc - size) & -4;
addr = loc;
type = func_vt;
vset(&type, VT_LOCAL | VT_LVAL, addr);
vswap();
vstore();
vset(&int_type, VT_LOCAL | VT_LVAL, addr);
}
vtop->type = int_type;
gv(RC_IRET);
} else {
#endif
type = func_vt;
mk_pointer(&type);
vset(&type, VT_LOCAL | VT_LVAL, func_vc);
indir();
vswap();
/* copy structure value to pointer */
vstore();
#ifdef TCC_ARM_EABI
}
#endif
} else if (is_float(func_vt.t)) {
gv(rc_fret(func_vt.t));
} else {
gv(RC_IRET);
}
vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
}
skip(';');
rsym = gjmp(rsym); /* jmp */
} else if (tok == TOK_BREAK) {
/* compute jump */
if (!bsym)
error("cannot break");
*bsym = gjmp(*bsym);
next();
skip(';');
} else if (tok == TOK_CONTINUE) {
/* compute jump */
if (!csym)
error("cannot continue");
*csym = gjmp(*csym);
next();
skip(';');
} else if (tok == TOK_FOR) {
int e;
next();
skip('(');
if (tok != ';') {
gexpr();
vpop();
}
skip(';');
d = ind;
c = ind;
a = 0;
b = 0;
if (tok != ';') {
gexpr();
a = gtst(1, 0);
}
skip(';');
if (tok != ')') {
e = gjmp(0);
c = ind;
gexpr();
vpop();
gjmp_addr(d);
gsym(e);
}
skip(')');
block(&a, &b, case_sym, def_sym, case_reg, 0);
gjmp_addr(c);
gsym(a);
gsym_addr(b, c);
} else
if (tok == TOK_DO) {
next();
a = 0;
b = 0;
d = ind;
block(&a, &b, case_sym, def_sym, case_reg, 0);
skip(TOK_WHILE);
skip('(');
gsym(b);
gexpr();
c = gtst(0, 0);
gsym_addr(c, d);
skip(')');
gsym(a);
skip(';');
} else
if (tok == TOK_SWITCH) {
next();
skip('(');
gexpr();
/* XXX: other types than integer */
case_reg = gv(RC_INT);
vpop();
skip(')');
a = 0;
b = gjmp(0); /* jump to first case */
c = 0;
block(&a, csym, &b, &c, case_reg, 0);
/* if no default, jmp after switch */
if (c == 0)
c = ind;
/* default label */
gsym_addr(b, c);
/* break label */
gsym(a);
} else
if (tok == TOK_CASE) {
int v1, v2;
if (!case_sym)
expect("switch");
next();
v1 = expr_const();
v2 = v1;
if (gnu_ext && tok == TOK_DOTS) {
next();
v2 = expr_const();
if (v2 < v1)
warning("empty case range");
}
/* since a case is like a label, we must skip it with a jmp */
b = gjmp(0);
gsym(*case_sym);
vseti(case_reg, 0);
vpushi(v1);
if (v1 == v2) {
gen_op(TOK_EQ);
*case_sym = gtst(1, 0);
} else {
gen_op(TOK_GE);
*case_sym = gtst(1, 0);
vseti(case_reg, 0);
vpushi(v2);
gen_op(TOK_LE);
*case_sym = gtst(1, *case_sym);
}
gsym(b);
skip(':');
is_expr = 0;
goto block_after_label;
} else
if (tok == TOK_DEFAULT) {
next();
skip(':');
if (!def_sym)
expect("switch");
if (*def_sym)
error("too many 'default'");
*def_sym = ind;
is_expr = 0;
goto block_after_label;
} else
if (tok == TOK_GOTO) {
next();
if (tok == '*' && gnu_ext) {
/* computed goto */
next();
gexpr();
if ((vtop->type.t & VT_BTYPE) != VT_PTR)
expect("pointer");
ggoto();
} else if (tok >= TOK_UIDENT) {
s = label_find(tok);
/* put forward definition if needed */
if (!s) {
s = label_push(&global_label_stack, tok, LABEL_FORWARD);
} else {
if (s->r == LABEL_DECLARED)
s->r = LABEL_FORWARD;
}
/* label already defined */
if (s->r & LABEL_FORWARD)
s->next = (void *)gjmp((long)s->next);
else
gjmp_addr((long)s->next);
next();
} else {
expect("label identifier");
}
skip(';');
} else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
asm_instr();
} else {
b = is_label();
if (b) {
/* label case */
s = label_find(b);
if (s) {
if (s->r == LABEL_DEFINED)
error("duplicate label '%s'", get_tok_str(s->v, NULL));
gsym((long)s->next);
s->r = LABEL_DEFINED;
} else {
s = label_push(&global_label_stack, b, LABEL_DEFINED);
}
s->next = (void *)ind;
/* we accept this, but it is a mistake */
block_after_label:
if (tok == '}') {
warning("deprecated use of label at end of compound statement");
} else {
if (is_expr)
vpop();
block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
}
} else {
/* expression case */
if (tok != ';') {
if (is_expr) {
vpop();
gexpr();
} else {
gexpr();
vpop();
}
}
skip(';');
}
}
}
/* t is the array or struct type. c is the array or struct
address. cur_index/cur_field is the pointer to the current
value. 'size_only' is true if only size info is needed (only used
in arrays) */
static void decl_designator(CType *type, Section *sec, unsigned long c,
int *cur_index, Sym **cur_field,
int size_only)
{
Sym *s, *f;
int notfirst, index, index_last, align, l, nb_elems, elem_size;
CType type1;
notfirst = 0;
elem_size = 0;
nb_elems = 1;
if (gnu_ext && (l = is_label()) != 0)
goto struct_field;
while (tok == '[' || tok == '.') {
if (tok == '[') {
if (!(type->t & VT_ARRAY))
expect("array type");
s = type->ref;
next();
index = expr_const();
if (index < 0 || (s->c >= 0 && index >= s->c))
expect("invalid index");
if (tok == TOK_DOTS && gnu_ext) {
next();
index_last = expr_const();
if (index_last < 0 ||
(s->c >= 0 && index_last >= s->c) ||
index_last < index)
expect("invalid index");
} else {
index_last = index;
}
skip(']');
if (!notfirst)
*cur_index = index_last;
type = pointed_type(type);
elem_size = type_size(type, &align);
c += index * elem_size;
/* NOTE: we only support ranges for last designator */
nb_elems = index_last - index + 1;
if (nb_elems != 1) {
notfirst = 1;
break;
}
} else {
next();
l = tok;
next();
struct_field:
if ((type->t & VT_BTYPE) != VT_STRUCT)
expect("struct/union type");
s = type->ref;
l |= SYM_FIELD;
f = s->next;
while (f) {
if (f->v == l)
break;
f = f->next;
}
if (!f)
expect("field");
if (!notfirst)
*cur_field = f;
/* XXX: fix this mess by using explicit storage field */
type1 = f->type;
type1.t |= (type->t & ~VT_TYPE);
type = &type1;
c += f->c;
}
notfirst = 1;
}
if (notfirst) {
if (tok == '=') {
next();
} else {
if (!gnu_ext)
expect("=");
}
} else {
if (type->t & VT_ARRAY) {
index = *cur_index;
type = pointed_type(type);
c += index * type_size(type, &align);
} else {
f = *cur_field;
if (!f)
error("too many field init");
/* XXX: fix this mess by using explicit storage field */
type1 = f->type;
type1.t |= (type->t & ~VT_TYPE);
type = &type1;
c += f->c;
}
}
decl_initializer(type, sec, c, 0, size_only);
/* XXX: make it more general */
if (!size_only && nb_elems > 1) {
unsigned long c_end;
uint8_t *src, *dst;
int i;
if (!sec)
error("range init not supported yet for dynamic storage");
c_end = c + nb_elems * elem_size;
if (c_end > sec->data_allocated)
section_realloc(sec, c_end);
src = sec->data + c;
dst = src;
for(i = 1; i < nb_elems; i++) {
dst += elem_size;
memcpy(dst, src, elem_size);
}
}
}
#define EXPR_VAL 0
#define EXPR_CONST 1
#define EXPR_ANY 2
/* store a value or an expression directly in global data or in local array */
static void init_putv(CType *type, Section *sec, unsigned long c,
int v, int expr_type)
{
int saved_global_expr, bt, bit_pos, bit_size;
void *ptr;
unsigned long long bit_mask;
CType dtype;
switch(expr_type) {
case EXPR_VAL:
vpushi(v);
break;
case EXPR_CONST:
/* compound literals must be allocated globally in this case */
saved_global_expr = global_expr;
global_expr = 1;
expr_const1();
global_expr = saved_global_expr;
/* NOTE: symbols are accepted */
if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
error("initializer element is not constant");
break;
case EXPR_ANY:
expr_eq();
break;
}
dtype = *type;
dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
if (sec) {
/* XXX: not portable */
/* XXX: generate error if incorrect relocation */
gen_assign_cast(&dtype);
bt = type->t & VT_BTYPE;
/* we'll write at most 12 bytes */
if (c + 12 > sec->data_allocated) {
section_realloc(sec, c + 12);
}
ptr = sec->data + c;
/* XXX: make code faster ? */
if (!(type->t & VT_BITFIELD)) {
bit_pos = 0;
bit_size = 32;
bit_mask = -1LL;
} else {
bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
bit_mask = (1LL << bit_size) - 1;
}
if ((vtop->r & VT_SYM) &&
(bt == VT_BYTE ||
bt == VT_SHORT ||
bt == VT_DOUBLE ||
bt == VT_LDOUBLE ||
bt == VT_LLONG ||
(bt == VT_INT && bit_size != 32)))
error("initializer element is not computable at load time");
switch(bt) {
case VT_BOOL:
vtop->c.i = (vtop->c.i != 0);
case VT_BYTE:
*(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
break;
case VT_SHORT:
*(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
break;
case VT_DOUBLE:
*(double *)ptr = vtop->c.d;
break;
case VT_LDOUBLE:
*(long double *)ptr = vtop->c.ld;
break;
case VT_LLONG:
*(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
break;
default:
if (vtop->r & VT_SYM) {
greloc(sec, vtop->sym, c, R_DATA_32);
}
*(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
break;
}
vtop--;
} else {
vset(&dtype, VT_LOCAL|VT_LVAL, c);
vswap();
vstore();
vpop();
}
}
/* put zeros for variable based init */
static void init_putz(CType *t, Section *sec, unsigned long c, int size)
{
if (sec) {
/* nothing to do because globals are already set to zero */
} else {
vpush_global_sym(&func_old_type, TOK_memset);
vseti(VT_LOCAL, c);
vpushi(0);
vpushi(size);
gfunc_call(3);
}
}
/* 't' contains the type and storage info. 'c' is the offset of the
object in section 'sec'. If 'sec' is NULL, it means stack based
allocation. 'first' is true if array '{' must be read (multi
dimension implicit array init handling). 'size_only' is true if
size only evaluation is wanted (only for arrays). */
static void decl_initializer(CType *type, Section *sec, unsigned long c,
int first, int size_only)
{
int index, array_length, n, no_oblock, nb, parlevel, i;
int size1, align1, expr_type;
Sym *s, *f;
CType *t1;
if (type->t & VT_ARRAY) {
s = type->ref;
n = s->c;
array_length = 0;
t1 = pointed_type(type);
size1 = type_size(t1, &align1);
no_oblock = 1;
if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
tok == '{') {
skip('{');
no_oblock = 0;
}
/* only parse strings here if correct type (otherwise: handle
them as ((w)char *) expressions */
if ((tok == TOK_LSTR &&
#ifdef TCC_TARGET_PE
(t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
#else
(t1->t & VT_BTYPE) == VT_INT
#endif
) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
while (tok == TOK_STR || tok == TOK_LSTR) {
int cstr_len, ch;
CString *cstr;
cstr = tokc.cstr;
/* compute maximum number of chars wanted */
if (tok == TOK_STR)
cstr_len = cstr->size;
else
cstr_len = cstr->size / sizeof(nwchar_t);
cstr_len--;
nb = cstr_len;
if (n >= 0 && nb > (n - array_length))
nb = n - array_length;
if (!size_only) {
if (cstr_len > nb)
warning("initializer-string for array is too long");
/* in order to go faster for common case (char
string in global variable, we handle it
specifically */
if (sec && tok == TOK_STR && size1 == 1) {
memcpy(sec->data + c + array_length, cstr->data, nb);
} else {
for(i=0;i<nb;i++) {
if (tok == TOK_STR)
ch = ((unsigned char *)cstr->data)[i];
else
ch = ((nwchar_t *)cstr->data)[i];
init_putv(t1, sec, c + (array_length + i) * size1,
ch, EXPR_VAL);
}
}
}
array_length += nb;
next();
}
/* only add trailing zero if enough storage (no
warning in this case since it is standard) */
if (n < 0 || array_length < n) {
if (!size_only) {
init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
}
array_length++;
}
} else {
index = 0;
while (tok != '}') {
decl_designator(type, sec, c, &index, NULL, size_only);
if (n >= 0 && index >= n)
error("index too large");
/* must put zero in holes (note that doing it that way
ensures that it even works with designators) */
if (!size_only && array_length < index) {
init_putz(t1, sec, c + array_length * size1,
(index - array_length) * size1);
}
index++;
if (index > array_length)
array_length = index;
/* special test for multi dimensional arrays (may not
be strictly correct if designators are used at the
same time) */
if (index >= n && no_oblock)
break;
if (tok == '}')
break;
skip(',');
}
}
if (!no_oblock)
skip('}');
/* put zeros at the end */
if (!size_only && n >= 0 && array_length < n) {
init_putz(t1, sec, c + array_length * size1,
(n - array_length) * size1);
}
/* patch type size if needed */
if (n < 0)
s->c = array_length;
} else if ((type->t & VT_BTYPE) == VT_STRUCT &&
(sec || !first || tok == '{')) {
int par_count;
/* NOTE: the previous test is a specific case for automatic
struct/union init */
/* XXX: union needs only one init */
/* XXX: this test is incorrect for local initializers
beginning with ( without {. It would be much more difficult
to do it correctly (ideally, the expression parser should
be used in all cases) */
par_count = 0;
if (tok == '(') {
AttributeDef ad1;
CType type1;
next();
while (tok == '(') {
par_count++;
next();
}
if (!parse_btype(&type1, &ad1))
expect("cast");
type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
#if 0
if (!is_assignable_types(type, &type1))
error("invalid type for cast");
#endif
skip(')');
}
no_oblock = 1;
if (first || tok == '{') {
skip('{');
no_oblock = 0;
}
s = type->ref;
f = s->next;
array_length = 0;
index = 0;
n = s->c;
while (tok != '}') {
decl_designator(type, sec, c, NULL, &f, size_only);
index = f->c;
if (!size_only && array_length < index) {
init_putz(type, sec, c + array_length,
index - array_length);
}
index = index + type_size(&f->type, &align1);
if (index > array_length)
array_length = index;
f = f->next;
if (no_oblock && f == NULL)
break;
if (tok == '}')
break;
skip(',');
}
/* put zeros at the end */
if (!size_only && array_length < n) {
init_putz(type, sec, c + array_length,
n - array_length);
}
if (!no_oblock)
skip('}');
while (par_count) {
skip(')');
par_count--;
}
} else if (tok == '{') {
next();
decl_initializer(type, sec, c, first, size_only);
skip('}');
} else if (size_only) {
/* just skip expression */
parlevel = 0;
while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
tok != -1) {
if (tok == '(')
parlevel++;
else if (tok == ')')
parlevel--;
next();
}
} else {
/* currently, we always use constant expression for globals
(may change for scripting case) */
expr_type = EXPR_CONST;
if (!sec)
expr_type = EXPR_ANY;
init_putv(type, sec, c, 0, expr_type);
}
}
/* parse an initializer for type 't' if 'has_init' is non zero, and
allocate space in local or global data space ('r' is either
VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
variable 'v' of scope 'scope' is declared before initializers are
parsed. If 'v' is zero, then a reference to the new object is put
in the value stack. If 'has_init' is 2, a special parsing is done
to handle string constants. */
static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
int has_init, int v, int scope)
{
int size, align, addr, data_offset;
int level;
ParseState saved_parse_state = {0};
TokenString init_str;
Section *sec;
size = type_size(type, &align);
/* If unknown size, we must evaluate it before
evaluating initializers because
initializers can generate global data too
(e.g. string pointers or ISOC99 compound
literals). It also simplifies local
initializers handling */
tok_str_new(&init_str);
if (size < 0) {
if (!has_init)
error("unknown type size");
/* get all init string */
if (has_init == 2) {
/* only get strings */
while (tok == TOK_STR || tok == TOK_LSTR) {
tok_str_add_tok(&init_str);
next();
}
} else {
level = 0;
while (level > 0 || (tok != ',' && tok != ';')) {
if (tok < 0)
error("unexpected end of file in initializer");
tok_str_add_tok(&init_str);
if (tok == '{')
level++;
else if (tok == '}') {
level--;
if (level <= 0) {
next();
break;
}
}
next();
}
}
tok_str_add(&init_str, -1);
tok_str_add(&init_str, 0);
/* compute size */
save_parse_state(&saved_parse_state);
macro_ptr = init_str.str;
next();
decl_initializer(type, NULL, 0, 1, 1);
/* prepare second initializer parsing */
macro_ptr = init_str.str;
next();
/* if still unknown size, error */
size = type_size(type, &align);
if (size < 0)
error("unknown type size");
}
/* take into account specified alignment if bigger */
if (ad->aligned) {
if (ad->aligned > align)
align = ad->aligned;
} else if (ad->packed) {
align = 1;
}
if ((r & VT_VALMASK) == VT_LOCAL) {
sec = NULL;
if (tcc_state->do_bounds_check && (type->t & VT_ARRAY))
loc--;
loc = (loc - size) & -align;
addr = loc;
/* handles bounds */
/* XXX: currently, since we do only one pass, we cannot track
'&' operators, so we add only arrays */
if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
unsigned long *bounds_ptr;
/* add padding between regions */
loc--;
/* then add local bound info */
bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
bounds_ptr[0] = addr;
bounds_ptr[1] = size;
}
if (v) {
/* local variable */
sym_push(v, type, r, addr);
} else {
/* push local reference */
vset(type, r, addr);
}
} else {
Sym *sym;
sym = NULL;
if (v && scope == VT_CONST) {
/* see if the symbol was already defined */
sym = sym_find(v);
if (sym) {
if (!is_compatible_types(&sym->type, type))
error("incompatible types for redefinition of '%s'",
get_tok_str(v, NULL));
if (sym->type.t & VT_EXTERN) {
/* if the variable is extern, it was not allocated */
sym->type.t &= ~VT_EXTERN;
/* set array size if it was ommited in extern
declaration */
if ((sym->type.t & VT_ARRAY) &&
sym->type.ref->c < 0 &&
type->ref->c >= 0)
sym->type.ref->c = type->ref->c;
} else {
/* we accept several definitions of the same
global variable. this is tricky, because we
must play with the SHN_COMMON type of the symbol */
/* XXX: should check if the variable was already
initialized. It is incorrect to initialized it
twice */
/* no init data, we won't add more to the symbol */
if (!has_init)
goto no_alloc;
}
}
}
/* allocate symbol in corresponding section */
sec = ad->section;
if (!sec) {
if (has_init)
sec = data_section;
else if (tcc_state->nocommon)
sec = bss_section;
}
if (sec) {
data_offset = sec->data_offset;
data_offset = (data_offset + align - 1) & -align;
addr = data_offset;
/* very important to increment global pointer at this time
because initializers themselves can create new initializers */
data_offset += size;
/* add padding if bound check */
if (tcc_state->do_bounds_check)
data_offset++;
sec->data_offset = data_offset;
/* allocate section space to put the data */
if (sec->sh_type != SHT_NOBITS &&
data_offset > sec->data_allocated)
section_realloc(sec, data_offset);
/* align section if needed */
if (align > sec->sh_addralign)
sec->sh_addralign = align;
} else {
addr = 0; /* avoid warning */
}
if (v) {
if (scope != VT_CONST || !sym) {
sym = sym_push(v, type, r | VT_SYM, 0);
}
/* update symbol definition */
if (sec) {
put_extern_sym(sym, sec, addr, size);
} else {
ElfW(Sym) *esym;
/* put a common area */
put_extern_sym(sym, NULL, align, size);
/* XXX: find a nicer way */
esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
esym->st_shndx = SHN_COMMON;
}
} else {
CValue cval;
/* push global reference */
sym = get_sym_ref(type, sec, addr, size);
cval.ul = 0;
vsetc(type, VT_CONST | VT_SYM, &cval);
vtop->sym = sym;
}
/* handles bounds now because the symbol must be defined
before for the relocation */
if (tcc_state->do_bounds_check) {
unsigned long *bounds_ptr;
greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
/* then add global bound info */
bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
bounds_ptr[0] = 0; /* relocated */
bounds_ptr[1] = size;
}
}
if (has_init) {
decl_initializer(type, sec, addr, 1, 0);
/* restore parse state if needed */
if (init_str.str) {
tok_str_free(init_str.str);
restore_parse_state(&saved_parse_state);
}
}
no_alloc: ;
}
void put_func_debug(Sym *sym)
{
char buf[512];
/* stabs info */
/* XXX: we put here a dummy type */
snprintf(buf, sizeof(buf), "%s:%c1",
funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
cur_text_section, sym->c);
/* //gr gdb wants a line at the function */
put_stabn(N_SLINE, 0, file->line_num, 0);
last_ind = 0;
last_line_num = 0;
}
/* parse an old style function declaration list */
/* XXX: check multiple parameter */
static void func_decl_list(Sym *func_sym)
{
AttributeDef ad;
int v;
Sym *s;
CType btype, type;
/* parse each declaration */
while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
if (!parse_btype(&btype, &ad))
expect("declaration list");
if (((btype.t & VT_BTYPE) == VT_ENUM ||
(btype.t & VT_BTYPE) == VT_STRUCT) &&
tok == ';') {
/* we accept no variable after */
} else {
for(;;) {
type = btype;
type_decl(&type, &ad, &v, TYPE_DIRECT);
/* find parameter in function parameter list */
s = func_sym->next;
while (s != NULL) {
if ((s->v & ~SYM_FIELD) == v)
goto found;
s = s->next;
}
error("declaration for parameter '%s' but no such parameter",
get_tok_str(v, NULL));
found:
/* check that no storage specifier except 'register' was given */
if (type.t & VT_STORAGE)
error("storage class specified for '%s'", get_tok_str(v, NULL));
convert_parameter_type(&type);
/* we can add the type (NOTE: it could be local to the function) */
s->type = type;
/* accept other parameters */
if (tok == ',')
next();
else
break;
}
}
skip(';');
}
}
/* parse a function defined by symbol 'sym' and generate its code in
'cur_text_section' */
static void gen_function(Sym *sym)
{
int saved_nocode_wanted = nocode_wanted;
nocode_wanted = 0;
ind = cur_text_section->data_offset;
/* NOTE: we patch the symbol size later */
put_extern_sym(sym, cur_text_section, ind, 0);
funcname = get_tok_str(sym->v, NULL);
func_ind = ind;
/* put debug symbol */
if (tcc_state->do_debug)
put_func_debug(sym);
/* push a dummy symbol to enable local sym storage */
sym_push2(&local_stack, SYM_FIELD, 0, 0);
gfunc_prolog(&sym->type);
rsym = 0;
block(NULL, NULL, NULL, NULL, 0, 0);
gsym(rsym);
gfunc_epilog();
cur_text_section->data_offset = ind;
label_pop(&global_label_stack, NULL);
sym_pop(&local_stack, NULL); /* reset local stack */
/* end of function */
/* patch symbol size */
((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
ind - func_ind;
if (tcc_state->do_debug) {
put_stabn(N_FUN, 0, 0, ind - func_ind);
}
/* It's better to crash than to generate wrong code */
cur_text_section = NULL;
funcname = ""; /* for safety */
func_vt.t = VT_VOID; /* for safety */
ind = 0; /* for safety */
nocode_wanted = saved_nocode_wanted;
}
static void gen_inline_functions(void)
{
Sym *sym;
CType *type;
int *str, inline_generated;
/* iterate while inline function are referenced */
for(;;) {
inline_generated = 0;
for(sym = global_stack; sym != NULL; sym = sym->prev) {
type = &sym->type;
if (((type->t & VT_BTYPE) == VT_FUNC) &&
(type->t & (VT_STATIC | VT_INLINE)) ==
(VT_STATIC | VT_INLINE) &&
sym->c != 0) {
/* the function was used: generate its code and
convert it to a normal function */
str = INLINE_DEF(sym->r);
sym->r = VT_SYM | VT_CONST;
sym->type.t &= ~VT_INLINE;
macro_ptr = str;
next();
cur_text_section = text_section;
gen_function(sym);
macro_ptr = NULL; /* fail safe */
tok_str_free(str);
inline_generated = 1;
}
}
if (!inline_generated)
break;
}
/* free all remaining inline function tokens */
for(sym = global_stack; sym != NULL; sym = sym->prev) {
type = &sym->type;
if (((type->t & VT_BTYPE) == VT_FUNC) &&
(type->t & (VT_STATIC | VT_INLINE)) ==
(VT_STATIC | VT_INLINE)) {
//gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
continue;
str = INLINE_DEF(sym->r);
tok_str_free(str);
sym->r = 0; /* fail safe */
}
}
}
/* 'l' is VT_LOCAL or VT_CONST to define default storage type */
static void decl(int l)
{
int v, has_init, r;
CType type, btype;
Sym *sym;
AttributeDef ad;
while (1) {
if (!parse_btype(&btype, &ad)) {
/* skip redundant ';' */
/* XXX: find more elegant solution */
if (tok == ';') {
next();
continue;
}
if (l == VT_CONST &&
(tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
/* global asm block */
asm_global_instr();
continue;
}
/* special test for old K&R protos without explicit int
type. Only accepted when defining global data */
if (l == VT_LOCAL || tok < TOK_DEFINE)
break;
btype.t = VT_INT;
}
if (((btype.t & VT_BTYPE) == VT_ENUM ||
(btype.t & VT_BTYPE) == VT_STRUCT) &&
tok == ';') {
/* we accept no variable after */
next();
continue;
}
while (1) { /* iterate thru each declaration */
type = btype;
type_decl(&type, &ad, &v, TYPE_DIRECT);
#if 0
{
char buf[500];
type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
printf("type = '%s'\n", buf);
}
#endif
if ((type.t & VT_BTYPE) == VT_FUNC) {
/* if old style function prototype, we accept a
declaration list */
sym = type.ref;
if (sym->c == FUNC_OLD)
func_decl_list(sym);
}
if (tok == '{') {
if (l == VT_LOCAL)
error("cannot use local functions");
if ((type.t & VT_BTYPE) != VT_FUNC)
expect("function definition");
/* reject abstract declarators in function definition */
sym = type.ref;
while ((sym = sym->next) != NULL)
if (!(sym->v & ~SYM_FIELD))
expect("identifier");
/* XXX: cannot do better now: convert extern line to static inline */
if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
sym = sym_find(v);
if (sym) {
if ((sym->type.t & VT_BTYPE) != VT_FUNC)
goto func_error1;
/* specific case: if not func_call defined, we put
the one of the prototype */
/* XXX: should have default value */
r = sym->type.ref->r;
if (FUNC_CALL(r) != FUNC_CDECL
&& FUNC_CALL(type.ref->r) == FUNC_CDECL)
FUNC_CALL(type.ref->r) = FUNC_CALL(r);
if (FUNC_EXPORT(r))
FUNC_EXPORT(type.ref->r) = 1;
if (!is_compatible_types(&sym->type, &type)) {
func_error1:
error("incompatible types for redefinition of '%s'",
get_tok_str(v, NULL));
}
/* if symbol is already defined, then put complete type */
sym->type = type;
} else {
/* put function symbol */
sym = global_identifier_push(v, type.t, 0);
sym->type.ref = type.ref;
}
/* static inline functions are just recorded as a kind
of macro. Their code will be emitted at the end of
the compilation unit only if they are used */
if ((type.t & (VT_INLINE | VT_STATIC)) ==
(VT_INLINE | VT_STATIC)) {
TokenString func_str;
int block_level;
tok_str_new(&func_str);
block_level = 0;
for(;;) {
int t;
if (tok == TOK_EOF)
error("unexpected end of file");
tok_str_add_tok(&func_str);
t = tok;
next();
if (t == '{') {
block_level++;
} else if (t == '}') {
block_level--;
if (block_level == 0)
break;
}
}
tok_str_add(&func_str, -1);
tok_str_add(&func_str, 0);
INLINE_DEF(sym->r) = func_str.str;
} else {
/* compute text section */
cur_text_section = ad.section;
if (!cur_text_section)
cur_text_section = text_section;
sym->r = VT_SYM | VT_CONST;
gen_function(sym);
}
break;
} else {
if (btype.t & VT_TYPEDEF) {
/* save typedefed type */
/* XXX: test storage specifiers ? */
sym = sym_push(v, &type, 0, 0);
sym->type.t |= VT_TYPEDEF;
} else if ((type.t & VT_BTYPE) == VT_FUNC) {
/* external function definition */
/* specific case for func_call attribute */
if (ad.func_attr)
type.ref->r = ad.func_attr;
external_sym(v, &type, 0);
} else {
/* not lvalue if array */
r = 0;
if (!(type.t & VT_ARRAY))
r |= lvalue_type(type.t);
has_init = (tok == '=');
if ((btype.t & VT_EXTERN) ||
((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
!has_init && l == VT_CONST && type.ref->c < 0)) {
/* external variable */
/* NOTE: as GCC, uninitialized global static
arrays of null size are considered as
extern */
external_sym(v, &type, r);
} else {
type.t |= (btype.t & VT_STATIC); /* Retain "static". */
if (type.t & VT_STATIC)
r |= VT_CONST;
else
r |= l;
if (has_init)
next();
decl_initializer_alloc(&type, &ad, r,
has_init, v, l);
}
}
if (tok != ',') {
skip(';');
break;
}
next();
}
}
}
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/tccgen.c | C | lgpl | 154,158 |
/*
* ELF file handling for TCC
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* This 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 of the License, or (at your option) any later version.
*
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef TCC_TARGET_X86_64
#define ElfW_Rel ElfW(Rela)
#define SHT_RELX SHT_RELA
#define REL_SECTION_FMT ".rela%s"
/* x86-64 requires PLT for DLLs */
#define TCC_OUTPUT_DLL_WITH_PLT
#else
#define ElfW_Rel ElfW(Rel)
#define SHT_RELX SHT_REL
#define REL_SECTION_FMT ".rel%s"
#endif
/* XXX: DLL with PLT would only work with x86-64 for now */
//#define TCC_OUTPUT_DLL_WITH_PLT
static int put_elf_str(Section *s, const char *sym)
{
int offset, len;
char *ptr;
len = strlen(sym) + 1;
offset = s->data_offset;
ptr = section_ptr_add(s, len);
memcpy(ptr, sym, len);
return offset;
}
/* elf symbol hashing function */
static unsigned long elf_hash(const unsigned char *name)
{
unsigned long h = 0, g;
while (*name) {
h = (h << 4) + *name++;
g = h & 0xf0000000;
if (g)
h ^= g >> 24;
h &= ~g;
}
return h;
}
/* rebuild hash table of section s */
/* NOTE: we do factorize the hash table code to go faster */
static void rebuild_hash(Section *s, unsigned int nb_buckets)
{
ElfW(Sym) *sym;
int *ptr, *hash, nb_syms, sym_index, h;
char *strtab;
strtab = s->link->data;
nb_syms = s->data_offset / sizeof(ElfW(Sym));
s->hash->data_offset = 0;
ptr = section_ptr_add(s->hash, (2 + nb_buckets + nb_syms) * sizeof(int));
ptr[0] = nb_buckets;
ptr[1] = nb_syms;
ptr += 2;
hash = ptr;
memset(hash, 0, (nb_buckets + 1) * sizeof(int));
ptr += nb_buckets + 1;
sym = (ElfW(Sym) *)s->data + 1;
for(sym_index = 1; sym_index < nb_syms; sym_index++) {
if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
h = elf_hash(strtab + sym->st_name) % nb_buckets;
*ptr = hash[h];
hash[h] = sym_index;
} else {
*ptr = 0;
}
ptr++;
sym++;
}
}
/* return the symbol number */
static int put_elf_sym(Section *s,
unsigned long value, unsigned long size,
int info, int other, int shndx, const char *name)
{
int name_offset, sym_index;
int nbuckets, h;
ElfW(Sym) *sym;
Section *hs;
sym = section_ptr_add(s, sizeof(ElfW(Sym)));
if (name)
name_offset = put_elf_str(s->link, name);
else
name_offset = 0;
/* XXX: endianness */
sym->st_name = name_offset;
sym->st_value = value;
sym->st_size = size;
sym->st_info = info;
sym->st_other = other;
sym->st_shndx = shndx;
sym_index = sym - (ElfW(Sym) *)s->data;
hs = s->hash;
if (hs) {
int *ptr, *base;
ptr = section_ptr_add(hs, sizeof(int));
base = (int *)hs->data;
/* only add global or weak symbols */
if (ELFW(ST_BIND)(info) != STB_LOCAL) {
/* add another hashing entry */
nbuckets = base[0];
h = elf_hash(name) % nbuckets;
*ptr = base[2 + h];
base[2 + h] = sym_index;
base[1]++;
/* we resize the hash table */
hs->nb_hashed_syms++;
if (hs->nb_hashed_syms > 2 * nbuckets) {
rebuild_hash(s, 2 * nbuckets);
}
} else {
*ptr = 0;
base[1]++;
}
}
return sym_index;
}
/* find global ELF symbol 'name' and return its index. Return 0 if not
found. */
static int find_elf_sym(Section *s, const char *name)
{
ElfW(Sym) *sym;
Section *hs;
int nbuckets, sym_index, h;
const char *name1;
hs = s->hash;
if (!hs)
return 0;
nbuckets = ((int *)hs->data)[0];
h = elf_hash(name) % nbuckets;
sym_index = ((int *)hs->data)[2 + h];
while (sym_index != 0) {
sym = &((ElfW(Sym) *)s->data)[sym_index];
name1 = s->link->data + sym->st_name;
if (!strcmp(name, name1))
return sym_index;
sym_index = ((int *)hs->data)[2 + nbuckets + sym_index];
}
return 0;
}
/* return elf symbol value or error */
void *tcc_get_symbol(TCCState *s, const char *name)
{
int sym_index;
ElfW(Sym) *sym;
sym_index = find_elf_sym(symtab_section, name);
if (!sym_index)
return NULL;
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
return (void*)(long)sym->st_value;
}
void *tcc_get_symbol_err(TCCState *s, const char *name)
{
void *sym;
sym = tcc_get_symbol(s, name);
if (!sym)
error("%s not defined", name);
return sym;
}
/* add an elf symbol : check if it is already defined and patch
it. Return symbol index. NOTE that sh_num can be SHN_UNDEF. */
static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
int info, int other, int sh_num, const char *name)
{
ElfW(Sym) *esym;
int sym_bind, sym_index, sym_type, esym_bind;
unsigned char sym_vis, esym_vis, new_vis;
sym_bind = ELFW(ST_BIND)(info);
sym_type = ELFW(ST_TYPE)(info);
sym_vis = ELFW(ST_VISIBILITY)(other);
if (sym_bind != STB_LOCAL) {
/* we search global or weak symbols */
sym_index = find_elf_sym(s, name);
if (!sym_index)
goto do_def;
esym = &((ElfW(Sym) *)s->data)[sym_index];
if (esym->st_shndx != SHN_UNDEF) {
esym_bind = ELFW(ST_BIND)(esym->st_info);
/* propagate the most constraining visibility */
/* STV_DEFAULT(0)<STV_PROTECTED(3)<STV_HIDDEN(2)<STV_INTERNAL(1) */
esym_vis = ELFW(ST_VISIBILITY)(esym->st_other);
if (esym_vis == STV_DEFAULT) {
new_vis = sym_vis;
} else if (sym_vis == STV_DEFAULT) {
new_vis = esym_vis;
} else {
new_vis = (esym_vis < sym_vis) ? esym_vis : sym_vis;
}
esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
| new_vis;
other = esym->st_other; /* in case we have to patch esym */
if (sh_num == SHN_UNDEF) {
/* ignore adding of undefined symbol if the
corresponding symbol is already defined */
} else if (sym_bind == STB_GLOBAL && esym_bind == STB_WEAK) {
/* global overrides weak, so patch */
goto do_patch;
} else if (sym_bind == STB_WEAK && esym_bind == STB_GLOBAL) {
/* weak is ignored if already global */
} else if (sym_vis == STV_HIDDEN || sym_vis == STV_INTERNAL) {
/* ignore hidden symbols after */
} else if (esym->st_shndx == SHN_COMMON && sh_num < SHN_LORESERVE) {
/* gr: Happens with 'tcc ... -static tcctest.c' on e.g. Ubuntu 6.01
No idea if this is the correct solution ... */
goto do_patch;
} else if (s == tcc_state->dynsymtab_section) {
/* we accept that two DLL define the same symbol */
} else {
#if 1
printf("new_bind=%x new_shndx=%x new_vis=%x old_bind=%x old_shndx=%x old_vis=%x\n",
sym_bind, sh_num, new_vis, esym_bind, esym->st_shndx, esym_vis);
#endif
error_noabort("'%s' defined twice", name);
}
} else {
do_patch:
esym->st_info = ELFW(ST_INFO)(sym_bind, sym_type);
esym->st_shndx = sh_num;
esym->st_value = value;
esym->st_size = size;
esym->st_other = other;
}
} else {
do_def:
sym_index = put_elf_sym(s, value, size,
ELFW(ST_INFO)(sym_bind, sym_type), other,
sh_num, name);
}
return sym_index;
}
/* put relocation */
static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
int type, int symbol)
{
char buf[256];
Section *sr;
ElfW_Rel *rel;
sr = s->reloc;
if (!sr) {
/* if no relocation section, create it */
snprintf(buf, sizeof(buf), REL_SECTION_FMT, s->name);
/* if the symtab is allocated, then we consider the relocation
are also */
sr = new_section(tcc_state, buf, SHT_RELX, symtab->sh_flags);
sr->sh_entsize = sizeof(ElfW_Rel);
sr->link = symtab;
sr->sh_info = s->sh_num;
s->reloc = sr;
}
rel = section_ptr_add(sr, sizeof(ElfW_Rel));
rel->r_offset = offset;
rel->r_info = ELFW(R_INFO)(symbol, type);
#ifdef TCC_TARGET_X86_64
rel->r_addend = 0;
#endif
}
/* put stab debug information */
typedef struct {
unsigned int n_strx; /* index into string table of name */
unsigned char n_type; /* type of symbol */
unsigned char n_other; /* misc info (usually empty) */
unsigned short n_desc; /* description field */
unsigned int n_value; /* value of symbol */
} Stab_Sym;
static void put_stabs(const char *str, int type, int other, int desc,
unsigned long value)
{
Stab_Sym *sym;
sym = section_ptr_add(stab_section, sizeof(Stab_Sym));
if (str) {
sym->n_strx = put_elf_str(stabstr_section, str);
} else {
sym->n_strx = 0;
}
sym->n_type = type;
sym->n_other = other;
sym->n_desc = desc;
sym->n_value = value;
}
static void put_stabs_r(const char *str, int type, int other, int desc,
unsigned long value, Section *sec, int sym_index)
{
put_stabs(str, type, other, desc, value);
put_elf_reloc(symtab_section, stab_section,
stab_section->data_offset - sizeof(unsigned int),
R_DATA_32, sym_index);
}
static void put_stabn(int type, int other, int desc, int value)
{
put_stabs(NULL, type, other, desc, value);
}
static void put_stabd(int type, int other, int desc)
{
put_stabs(NULL, type, other, desc, 0);
}
/* In an ELF file symbol table, the local symbols must appear below
the global and weak ones. Since TCC cannot sort it while generating
the code, we must do it after. All the relocation tables are also
modified to take into account the symbol table sorting */
static void sort_syms(TCCState *s1, Section *s)
{
int *old_to_new_syms;
ElfW(Sym) *new_syms;
int nb_syms, i;
ElfW(Sym) *p, *q;
ElfW_Rel *rel, *rel_end;
Section *sr;
int type, sym_index;
nb_syms = s->data_offset / sizeof(ElfW(Sym));
new_syms = tcc_malloc(nb_syms * sizeof(ElfW(Sym)));
old_to_new_syms = tcc_malloc(nb_syms * sizeof(int));
/* first pass for local symbols */
p = (ElfW(Sym) *)s->data;
q = new_syms;
for(i = 0; i < nb_syms; i++) {
if (ELFW(ST_BIND)(p->st_info) == STB_LOCAL) {
old_to_new_syms[i] = q - new_syms;
*q++ = *p;
}
p++;
}
/* save the number of local symbols in section header */
s->sh_info = q - new_syms;
/* then second pass for non local symbols */
p = (ElfW(Sym) *)s->data;
for(i = 0; i < nb_syms; i++) {
if (ELFW(ST_BIND)(p->st_info) != STB_LOCAL) {
old_to_new_syms[i] = q - new_syms;
*q++ = *p;
}
p++;
}
/* we copy the new symbols to the old */
memcpy(s->data, new_syms, nb_syms * sizeof(ElfW(Sym)));
tcc_free(new_syms);
/* now we modify all the relocations */
for(i = 1; i < s1->nb_sections; i++) {
sr = s1->sections[i];
if (sr->sh_type == SHT_RELX && sr->link == s) {
rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
for(rel = (ElfW_Rel *)sr->data;
rel < rel_end;
rel++) {
sym_index = ELFW(R_SYM)(rel->r_info);
type = ELFW(R_TYPE)(rel->r_info);
sym_index = old_to_new_syms[sym_index];
rel->r_info = ELFW(R_INFO)(sym_index, type);
}
}
}
tcc_free(old_to_new_syms);
}
/* relocate common symbols in the .bss section */
static void relocate_common_syms(void)
{
ElfW(Sym) *sym, *sym_end;
unsigned long offset, align;
sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
for(sym = (ElfW(Sym) *)symtab_section->data + 1;
sym < sym_end;
sym++) {
if (sym->st_shndx == SHN_COMMON) {
/* align symbol */
align = sym->st_value;
offset = bss_section->data_offset;
offset = (offset + align - 1) & -align;
sym->st_value = offset;
sym->st_shndx = bss_section->sh_num;
offset += sym->st_size;
bss_section->data_offset = offset;
}
}
}
/* relocate symbol table, resolve undefined symbols if do_resolve is
true and output error if undefined symbol. */
static void relocate_syms(TCCState *s1, int do_resolve)
{
ElfW(Sym) *sym, *esym, *sym_end;
int sym_bind, sh_num, sym_index;
const char *name;
unsigned long addr;
sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
for(sym = (ElfW(Sym) *)symtab_section->data + 1;
sym < sym_end;
sym++) {
sh_num = sym->st_shndx;
if (sh_num == SHN_UNDEF) {
name = strtab_section->data + sym->st_name;
if (do_resolve) {
name = symtab_section->link->data + sym->st_name;
addr = (unsigned long)resolve_sym(s1, name, ELFW(ST_TYPE)(sym->st_info));
if (addr) {
sym->st_value = addr;
goto found;
}
} else if (s1->dynsym) {
/* if dynamic symbol exist, then use it */
sym_index = find_elf_sym(s1->dynsym, name);
if (sym_index) {
esym = &((ElfW(Sym) *)s1->dynsym->data)[sym_index];
sym->st_value = esym->st_value;
goto found;
}
}
/* XXX: _fp_hw seems to be part of the ABI, so we ignore
it */
if (!strcmp(name, "_fp_hw"))
goto found;
/* only weak symbols are accepted to be undefined. Their
value is zero */
sym_bind = ELFW(ST_BIND)(sym->st_info);
if (sym_bind == STB_WEAK) {
sym->st_value = 0;
} else {
error_noabort("undefined symbol '%s'", name);
}
} else if (sh_num < SHN_LORESERVE) {
/* add section base */
sym->st_value += s1->sections[sym->st_shndx]->sh_addr;
}
found: ;
}
}
#ifdef TCC_TARGET_X86_64
#define JMP_TABLE_ENTRY_SIZE 14
static unsigned long add_jmp_table(TCCState *s1, unsigned long val)
{
char *p = s1->runtime_plt_and_got + s1->runtime_plt_and_got_offset;
s1->runtime_plt_and_got_offset += JMP_TABLE_ENTRY_SIZE;
/* jmp *0x0(%rip) */
p[0] = 0xff;
p[1] = 0x25;
*(int *)(p + 2) = 0;
*(unsigned long *)(p + 6) = val;
return (unsigned long)p;
}
static unsigned long add_got_table(TCCState *s1, unsigned long val)
{
unsigned long *p =(unsigned long *)(s1->runtime_plt_and_got +
s1->runtime_plt_and_got_offset);
s1->runtime_plt_and_got_offset += sizeof(void *);
*p = val;
return (unsigned long)p;
}
#endif
/* relocate a given section (CPU dependent) */
static void relocate_section(TCCState *s1, Section *s)
{
Section *sr;
ElfW_Rel *rel, *rel_end, *qrel;
ElfW(Sym) *sym;
int type, sym_index;
unsigned char *ptr;
unsigned long val, addr;
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
int esym_index;
#endif
sr = s->reloc;
rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
qrel = (ElfW_Rel *)sr->data;
for(rel = qrel;
rel < rel_end;
rel++) {
ptr = s->data + rel->r_offset;
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
val = sym->st_value;
#ifdef TCC_TARGET_X86_64
/* XXX: not tested */
val += rel->r_addend;
#endif
type = ELFW(R_TYPE)(rel->r_info);
addr = s->sh_addr + rel->r_offset;
/* CPU specific */
switch(type) {
#if defined(TCC_TARGET_I386)
case R_386_32:
if (s1->output_type == TCC_OUTPUT_DLL) {
esym_index = s1->symtab_to_dynsym[sym_index];
qrel->r_offset = rel->r_offset;
if (esym_index) {
qrel->r_info = ELFW(R_INFO)(esym_index, R_386_32);
qrel++;
break;
} else {
qrel->r_info = ELFW(R_INFO)(0, R_386_RELATIVE);
qrel++;
}
}
*(int *)ptr += val;
break;
case R_386_PC32:
if (s1->output_type == TCC_OUTPUT_DLL) {
/* DLL relocation */
esym_index = s1->symtab_to_dynsym[sym_index];
if (esym_index) {
qrel->r_offset = rel->r_offset;
qrel->r_info = ELFW(R_INFO)(esym_index, R_386_PC32);
qrel++;
break;
}
}
*(int *)ptr += val - addr;
break;
case R_386_PLT32:
*(int *)ptr += val - addr;
break;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
*(int *)ptr = val;
break;
case R_386_GOTPC:
*(int *)ptr += s1->got->sh_addr - addr;
break;
case R_386_GOTOFF:
*(int *)ptr += val - s1->got->sh_addr;
break;
case R_386_GOT32:
/* we load the got offset */
*(int *)ptr += s1->got_offsets[sym_index];
break;
#elif defined(TCC_TARGET_ARM)
case R_ARM_PC24:
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PLT32:
{
int x;
x = (*(int *)ptr)&0xffffff;
(*(int *)ptr) &= 0xff000000;
if (x & 0x800000)
x -= 0x1000000;
x *= 4;
x += val - addr;
if((x & 3) != 0 || x >= 0x4000000 || x < -0x4000000)
error("can't relocate value at %x",addr);
x >>= 2;
x &= 0xffffff;
(*(int *)ptr) |= x;
}
break;
case R_ARM_PREL31:
{
int x;
x = (*(int *)ptr) & 0x7fffffff;
(*(int *)ptr) &= 0x80000000;
x = (x * 2) / 2;
x += val - addr;
if((x^(x>>1))&0x40000000)
error("can't relocate value at %x",addr);
(*(int *)ptr) |= x & 0x7fffffff;
}
case R_ARM_ABS32:
*(int *)ptr += val;
break;
case R_ARM_BASE_PREL:
*(int *)ptr += s1->got->sh_addr - addr;
break;
case R_ARM_GOTOFF32:
*(int *)ptr += val - s1->got->sh_addr;
break;
case R_ARM_GOT_BREL:
/* we load the got offset */
*(int *)ptr += s1->got_offsets[sym_index];
break;
case R_ARM_COPY:
break;
default:
fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n",
type,addr,(unsigned int )ptr,val);
break;
#elif defined(TCC_TARGET_C67)
case R_C60_32:
*(int *)ptr += val;
break;
case R_C60LO16:
{
uint32_t orig;
/* put the low 16 bits of the absolute address */
// add to what is already there
orig = ((*(int *)(ptr )) >> 7) & 0xffff;
orig |= (((*(int *)(ptr+4)) >> 7) & 0xffff) << 16;
//patch both at once - assumes always in pairs Low - High
*(int *) ptr = (*(int *) ptr & (~(0xffff << 7)) ) | (((val+orig) & 0xffff) << 7);
*(int *)(ptr+4) = (*(int *)(ptr+4) & (~(0xffff << 7)) ) | ((((val+orig)>>16) & 0xffff) << 7);
}
break;
case R_C60HI16:
break;
default:
fprintf(stderr,"FIXME: handle reloc type %x at %lx [%.8x] to %lx\n",
type,addr,(unsigned int )ptr,val);
break;
#elif defined(TCC_TARGET_X86_64)
case R_X86_64_64:
if (s1->output_type == TCC_OUTPUT_DLL) {
qrel->r_info = ELFW(R_INFO)(0, R_X86_64_RELATIVE);
qrel->r_addend = *(long long *)ptr + val;
qrel++;
}
*(long long *)ptr += val;
break;
case R_X86_64_32:
case R_X86_64_32S:
if (s1->output_type == TCC_OUTPUT_DLL) {
/* XXX: this logic may depend on TCC's codegen
now TCC uses R_X86_64_32 even for a 64bit pointer */
qrel->r_info = ELFW(R_INFO)(0, R_X86_64_RELATIVE);
qrel->r_addend = *(int *)ptr + val;
qrel++;
}
*(int *)ptr += val;
break;
case R_X86_64_PC32: {
if (s1->output_type == TCC_OUTPUT_DLL) {
/* DLL relocation */
esym_index = s1->symtab_to_dynsym[sym_index];
if (esym_index) {
qrel->r_offset = rel->r_offset;
qrel->r_info = ELFW(R_INFO)(esym_index, R_X86_64_PC32);
qrel->r_addend = *(int *)ptr;
qrel++;
break;
}
}
long diff = val - addr;
if (diff <= -2147483647 || diff > 2147483647) {
/* XXX: naive support for over 32bit jump */
if (s1->output_type == TCC_OUTPUT_MEMORY) {
val = add_jmp_table(s1, val);
diff = val - addr;
}
if (diff <= -2147483647 || diff > 2147483647) {
error("internal error: relocation failed");
}
}
*(int *)ptr += diff;
}
break;
case R_X86_64_PLT32:
*(int *)ptr += val - addr;
break;
case R_X86_64_GLOB_DAT:
case R_X86_64_JUMP_SLOT:
*(int *)ptr = val;
break;
case R_X86_64_GOTPCREL:
if (s1->output_type == TCC_OUTPUT_MEMORY) {
val = add_got_table(s1, val - rel->r_addend) + rel->r_addend;
*(int *)ptr += val - addr;
break;
}
*(int *)ptr += (s1->got->sh_addr - addr +
s1->got_offsets[sym_index] - 4);
break;
case R_X86_64_GOTTPOFF:
*(int *)ptr += val - s1->got->sh_addr;
break;
case R_X86_64_GOT32:
/* we load the got offset */
*(int *)ptr += s1->got_offsets[sym_index];
break;
#else
#error unsupported processor
#endif
}
}
/* if the relocation is allocated, we change its symbol table */
if (sr->sh_flags & SHF_ALLOC)
sr->link = s1->dynsym;
}
/* relocate relocation table in 'sr' */
static void relocate_rel(TCCState *s1, Section *sr)
{
Section *s;
ElfW_Rel *rel, *rel_end;
s = s1->sections[sr->sh_info];
rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
for(rel = (ElfW_Rel *)sr->data;
rel < rel_end;
rel++) {
rel->r_offset += s->sh_addr;
}
}
/* count the number of dynamic relocations so that we can reserve
their space */
static int prepare_dynamic_rel(TCCState *s1, Section *sr)
{
ElfW_Rel *rel, *rel_end;
int sym_index, esym_index, type, count;
count = 0;
rel_end = (ElfW_Rel *)(sr->data + sr->data_offset);
for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) {
sym_index = ELFW(R_SYM)(rel->r_info);
type = ELFW(R_TYPE)(rel->r_info);
switch(type) {
#if defined(TCC_TARGET_I386)
case R_386_32:
#elif defined(TCC_TARGET_X86_64)
case R_X86_64_32:
case R_X86_64_32S:
case R_X86_64_64:
#endif
count++;
break;
#if defined(TCC_TARGET_I386)
case R_386_PC32:
#elif defined(TCC_TARGET_X86_64)
case R_X86_64_PC32:
#endif
esym_index = s1->symtab_to_dynsym[sym_index];
if (esym_index)
count++;
break;
default:
break;
}
}
if (count) {
/* allocate the section */
sr->sh_flags |= SHF_ALLOC;
sr->sh_size = count * sizeof(ElfW_Rel);
}
return count;
}
static void put_got_offset(TCCState *s1, int index, unsigned long val)
{
int n;
unsigned long *tab;
if (index >= s1->nb_got_offsets) {
/* find immediately bigger power of 2 and reallocate array */
n = 1;
while (index >= n)
n *= 2;
tab = tcc_realloc(s1->got_offsets, n * sizeof(unsigned long));
if (!tab)
error("memory full");
s1->got_offsets = tab;
memset(s1->got_offsets + s1->nb_got_offsets, 0,
(n - s1->nb_got_offsets) * sizeof(unsigned long));
s1->nb_got_offsets = n;
}
s1->got_offsets[index] = val;
}
/* XXX: suppress that */
static void put32(unsigned char *p, uint32_t val)
{
p[0] = val;
p[1] = val >> 8;
p[2] = val >> 16;
p[3] = val >> 24;
}
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_ARM) || \
defined(TCC_TARGET_X86_64)
static uint32_t get32(unsigned char *p)
{
return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
}
#endif
static void build_got(TCCState *s1)
{
unsigned char *ptr;
/* if no got, then create it */
s1->got = new_section(s1, ".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
s1->got->sh_entsize = 4;
add_elf_sym(symtab_section, 0, 4, ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
0, s1->got->sh_num, "_GLOBAL_OFFSET_TABLE_");
ptr = section_ptr_add(s1->got, 3 * PTR_SIZE);
#if PTR_SIZE == 4
/* keep space for _DYNAMIC pointer, if present */
put32(ptr, 0);
/* two dummy got entries */
put32(ptr + 4, 0);
put32(ptr + 8, 0);
#else
/* keep space for _DYNAMIC pointer, if present */
put32(ptr, 0);
put32(ptr + 4, 0);
/* two dummy got entries */
put32(ptr + 8, 0);
put32(ptr + 12, 0);
put32(ptr + 16, 0);
put32(ptr + 20, 0);
#endif
}
/* put a got entry corresponding to a symbol in symtab_section. 'size'
and 'info' can be modifed if more precise info comes from the DLL */
static void put_got_entry(TCCState *s1,
int reloc_type, unsigned long size, int info,
int sym_index)
{
int index;
const char *name;
ElfW(Sym) *sym;
unsigned long offset;
int *ptr;
if (!s1->got)
build_got(s1);
/* if a got entry already exists for that symbol, no need to add one */
if (sym_index < s1->nb_got_offsets &&
s1->got_offsets[sym_index] != 0)
return;
put_got_offset(s1, sym_index, s1->got->data_offset);
if (s1->dynsym) {
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
name = symtab_section->link->data + sym->st_name;
offset = sym->st_value;
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
if (reloc_type ==
#ifdef TCC_TARGET_X86_64
R_X86_64_JUMP_SLOT
#else
R_386_JMP_SLOT
#endif
) {
Section *plt;
uint8_t *p;
int modrm;
#if defined(TCC_OUTPUT_DLL_WITH_PLT)
modrm = 0x25;
#else
/* if we build a DLL, we add a %ebx offset */
if (s1->output_type == TCC_OUTPUT_DLL)
modrm = 0xa3;
else
modrm = 0x25;
#endif
/* add a PLT entry */
plt = s1->plt;
if (plt->data_offset == 0) {
/* first plt entry */
p = section_ptr_add(plt, 16);
p[0] = 0xff; /* pushl got + PTR_SIZE */
p[1] = modrm + 0x10;
put32(p + 2, PTR_SIZE);
p[6] = 0xff; /* jmp *(got + PTR_SIZE * 2) */
p[7] = modrm;
put32(p + 8, PTR_SIZE * 2);
}
p = section_ptr_add(plt, 16);
p[0] = 0xff; /* jmp *(got + x) */
p[1] = modrm;
put32(p + 2, s1->got->data_offset);
p[6] = 0x68; /* push $xxx */
put32(p + 7, (plt->data_offset - 32) >> 1);
p[11] = 0xe9; /* jmp plt_start */
put32(p + 12, -(plt->data_offset));
/* the symbol is modified so that it will be relocated to
the PLT */
#if !defined(TCC_OUTPUT_DLL_WITH_PLT)
if (s1->output_type == TCC_OUTPUT_EXE)
#endif
offset = plt->data_offset - 16;
}
#elif defined(TCC_TARGET_ARM)
if (reloc_type == R_ARM_JUMP_SLOT) {
Section *plt;
uint8_t *p;
/* if we build a DLL, we add a %ebx offset */
if (s1->output_type == TCC_OUTPUT_DLL)
error("DLLs unimplemented!");
/* add a PLT entry */
plt = s1->plt;
if (plt->data_offset == 0) {
/* first plt entry */
p = section_ptr_add(plt, 16);
put32(p , 0xe52de004);
put32(p + 4, 0xe59fe010);
put32(p + 8, 0xe08fe00e);
put32(p + 12, 0xe5bef008);
}
p = section_ptr_add(plt, 16);
put32(p , 0xe59fc004);
put32(p+4, 0xe08fc00c);
put32(p+8, 0xe59cf000);
put32(p+12, s1->got->data_offset);
/* the symbol is modified so that it will be relocated to
the PLT */
if (s1->output_type == TCC_OUTPUT_EXE)
offset = plt->data_offset - 16;
}
#elif defined(TCC_TARGET_C67)
error("C67 got not implemented");
#else
#error unsupported CPU
#endif
index = put_elf_sym(s1->dynsym, offset,
size, info, 0, sym->st_shndx, name);
/* put a got entry */
put_elf_reloc(s1->dynsym, s1->got,
s1->got->data_offset,
reloc_type, index);
}
ptr = section_ptr_add(s1->got, PTR_SIZE);
*ptr = 0;
}
/* build GOT and PLT entries */
static void build_got_entries(TCCState *s1)
{
Section *s, *symtab;
ElfW_Rel *rel, *rel_end;
ElfW(Sym) *sym;
int i, type, reloc_type, sym_index;
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (s->sh_type != SHT_RELX)
continue;
/* no need to handle got relocations */
if (s->link != symtab_section)
continue;
symtab = s->link;
rel_end = (ElfW_Rel *)(s->data + s->data_offset);
for(rel = (ElfW_Rel *)s->data;
rel < rel_end;
rel++) {
type = ELFW(R_TYPE)(rel->r_info);
switch(type) {
#if defined(TCC_TARGET_I386)
case R_386_GOT32:
case R_386_GOTOFF:
case R_386_GOTPC:
case R_386_PLT32:
if (!s1->got)
build_got(s1);
if (type == R_386_GOT32 || type == R_386_PLT32) {
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
/* look at the symbol got offset. If none, then add one */
if (type == R_386_GOT32)
reloc_type = R_386_GLOB_DAT;
else
reloc_type = R_386_JMP_SLOT;
put_got_entry(s1, reloc_type, sym->st_size, sym->st_info,
sym_index);
}
break;
#elif defined(TCC_TARGET_ARM)
case R_ARM_GOT_BREL:
case R_ARM_GOTOFF32:
case R_ARM_BASE_PREL:
case R_ARM_PLT32:
if (!s1->got)
build_got(s1);
if (type == R_ARM_GOT_BREL || type == R_ARM_PLT32) {
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
/* look at the symbol got offset. If none, then add one */
if (type == R_ARM_GOT_BREL)
reloc_type = R_ARM_GLOB_DAT;
else
reloc_type = R_ARM_JUMP_SLOT;
put_got_entry(s1, reloc_type, sym->st_size, sym->st_info,
sym_index);
}
break;
#elif defined(TCC_TARGET_C67)
case R_C60_GOT32:
case R_C60_GOTOFF:
case R_C60_GOTPC:
case R_C60_PLT32:
if (!s1->got)
build_got(s1);
if (type == R_C60_GOT32 || type == R_C60_PLT32) {
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
/* look at the symbol got offset. If none, then add one */
if (type == R_C60_GOT32)
reloc_type = R_C60_GLOB_DAT;
else
reloc_type = R_C60_JMP_SLOT;
put_got_entry(s1, reloc_type, sym->st_size, sym->st_info,
sym_index);
}
break;
#elif defined(TCC_TARGET_X86_64)
case R_X86_64_GOT32:
case R_X86_64_GOTTPOFF:
case R_X86_64_GOTPCREL:
case R_X86_64_PLT32:
if (!s1->got)
build_got(s1);
if (type == R_X86_64_GOT32 || type == R_X86_64_GOTPCREL ||
type == R_X86_64_PLT32) {
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
/* look at the symbol got offset. If none, then add one */
if (type == R_X86_64_GOT32 || type == R_X86_64_GOTPCREL)
reloc_type = R_X86_64_GLOB_DAT;
else
reloc_type = R_X86_64_JUMP_SLOT;
put_got_entry(s1, reloc_type, sym->st_size, sym->st_info,
sym_index);
}
break;
#else
#error unsupported CPU
#endif
default:
break;
}
}
}
}
static Section *new_symtab(TCCState *s1,
const char *symtab_name, int sh_type, int sh_flags,
const char *strtab_name,
const char *hash_name, int hash_sh_flags)
{
Section *symtab, *strtab, *hash;
int *ptr, nb_buckets;
symtab = new_section(s1, symtab_name, sh_type, sh_flags);
symtab->sh_entsize = sizeof(ElfW(Sym));
strtab = new_section(s1, strtab_name, SHT_STRTAB, sh_flags);
put_elf_str(strtab, "");
symtab->link = strtab;
put_elf_sym(symtab, 0, 0, 0, 0, 0, NULL);
nb_buckets = 1;
hash = new_section(s1, hash_name, SHT_HASH, hash_sh_flags);
hash->sh_entsize = sizeof(int);
symtab->hash = hash;
hash->link = symtab;
ptr = section_ptr_add(hash, (2 + nb_buckets + 1) * sizeof(int));
ptr[0] = nb_buckets;
ptr[1] = 1;
memset(ptr + 2, 0, (nb_buckets + 1) * sizeof(int));
return symtab;
}
/* put dynamic tag */
static void put_dt(Section *dynamic, int dt, unsigned long val)
{
ElfW(Dyn) *dyn;
dyn = section_ptr_add(dynamic, sizeof(ElfW(Dyn)));
dyn->d_tag = dt;
dyn->d_un.d_val = val;
}
static void add_init_array_defines(TCCState *s1, const char *section_name)
{
Section *s;
long end_offset;
char sym_start[1024];
char sym_end[1024];
snprintf(sym_start, sizeof(sym_start), "__%s_start", section_name + 1);
snprintf(sym_end, sizeof(sym_end), "__%s_end", section_name + 1);
s = find_section(s1, section_name);
if (!s) {
end_offset = 0;
s = data_section;
} else {
end_offset = s->data_offset;
}
add_elf_sym(symtab_section,
0, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
s->sh_num, sym_start);
add_elf_sym(symtab_section,
end_offset, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
s->sh_num, sym_end);
}
/* add tcc runtime libraries */
static void tcc_add_runtime(TCCState *s1)
{
#if defined(CONFIG_TCC_BCHECK) || !defined(CONFIG_USE_LIBGCC)
char buf[1024];
#endif
#ifdef CONFIG_TCC_BCHECK
if (s1->do_bounds_check) {
unsigned long *ptr;
Section *init_section;
unsigned char *pinit;
int sym_index;
/* XXX: add an object file to do that */
ptr = section_ptr_add(bounds_section, sizeof(unsigned long));
*ptr = 0;
add_elf_sym(symtab_section, 0, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
bounds_section->sh_num, "__bounds_start");
/* add bound check code */
snprintf(buf, sizeof(buf), "%s/%s", s1->tcc_lib_path, "bcheck.o");
tcc_add_file(s1, buf);
#ifdef TCC_TARGET_I386
if (s1->output_type != TCC_OUTPUT_MEMORY) {
/* add 'call __bound_init()' in .init section */
init_section = find_section(s1, ".init");
pinit = section_ptr_add(init_section, 5);
pinit[0] = 0xe8;
put32(pinit + 1, -4);
sym_index = find_elf_sym(symtab_section, "__bound_init");
put_elf_reloc(symtab_section, init_section,
init_section->data_offset - 4, R_386_PC32, sym_index);
}
#endif
}
#endif
/* add libc */
if (!s1->nostdlib) {
tcc_add_library(s1, "c");
#ifdef CONFIG_USE_LIBGCC
tcc_add_file(s1, CONFIG_SYSROOT "/lib/libgcc_s.so.1");
#else
snprintf(buf, sizeof(buf), "%s/%s", s1->tcc_lib_path, "libtcc1.a");
tcc_add_file(s1, buf);
#endif
}
/* add crt end if not memory output */
if (s1->output_type != TCC_OUTPUT_MEMORY && !s1->nostdlib) {
tcc_add_file(s1, CONFIG_TCC_CRT_PREFIX "/crtn.o");
}
}
/* add various standard linker symbols (must be done after the
sections are filled (for example after allocating common
symbols)) */
static void tcc_add_linker_symbols(TCCState *s1)
{
char buf[1024];
int i;
Section *s;
add_elf_sym(symtab_section,
text_section->data_offset, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
text_section->sh_num, "_etext");
add_elf_sym(symtab_section,
data_section->data_offset, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
data_section->sh_num, "_edata");
add_elf_sym(symtab_section,
bss_section->data_offset, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
bss_section->sh_num, "_end");
/* horrible new standard ldscript defines */
add_init_array_defines(s1, ".preinit_array");
add_init_array_defines(s1, ".init_array");
add_init_array_defines(s1, ".fini_array");
/* add start and stop symbols for sections whose name can be
expressed in C */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (s->sh_type == SHT_PROGBITS &&
(s->sh_flags & SHF_ALLOC)) {
const char *p;
int ch;
/* check if section name can be expressed in C */
p = s->name;
for(;;) {
ch = *p;
if (!ch)
break;
if (!isid(ch) && !isnum(ch))
goto next_sec;
p++;
}
snprintf(buf, sizeof(buf), "__start_%s", s->name);
add_elf_sym(symtab_section,
0, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
s->sh_num, buf);
snprintf(buf, sizeof(buf), "__stop_%s", s->name);
add_elf_sym(symtab_section,
s->data_offset, 0,
ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
s->sh_num, buf);
}
next_sec: ;
}
}
/* name of ELF interpreter */
#if defined __FreeBSD__
static char elf_interp[] = "/usr/libexec/ld-elf.so.1";
#elif defined TCC_ARM_EABI
static char elf_interp[] = "/lib/ld-linux.so.3";
#elif defined(TCC_TARGET_X86_64)
static char elf_interp[] = "/lib/ld-linux-x86-64.so.2";
#elif defined(TCC_UCLIBC)
static char elf_interp[] = "/lib/ld-uClibc.so.0";
#else
static char elf_interp[] = "/lib/ld-linux.so.2";
#endif
static void tcc_output_binary(TCCState *s1, FILE *f,
const int *section_order)
{
Section *s;
int i, offset, size;
offset = 0;
for(i=1;i<s1->nb_sections;i++) {
s = s1->sections[section_order[i]];
if (s->sh_type != SHT_NOBITS &&
(s->sh_flags & SHF_ALLOC)) {
while (offset < s->sh_offset) {
fputc(0, f);
offset++;
}
size = s->sh_size;
fwrite(s->data, 1, size, f);
offset += size;
}
}
}
/* output an ELF file */
/* XXX: suppress unneeded sections */
int elf_output_file(TCCState *s1, const char *filename)
{
ElfW(Ehdr) ehdr;
FILE *f;
int fd, mode, ret;
int *section_order;
int shnum, i, phnum, file_offset, offset, size, j, tmp, sh_order_index, k;
unsigned long addr;
Section *strsec, *s;
ElfW(Shdr) shdr, *sh;
ElfW(Phdr) *phdr, *ph;
Section *interp, *dynamic, *dynstr;
unsigned long saved_dynamic_data_offset;
ElfW(Sym) *sym;
int type, file_type;
unsigned long rel_addr, rel_size;
file_type = s1->output_type;
s1->nb_errors = 0;
if (file_type != TCC_OUTPUT_OBJ) {
tcc_add_runtime(s1);
}
phdr = NULL;
section_order = NULL;
interp = NULL;
dynamic = NULL;
dynstr = NULL; /* avoid warning */
saved_dynamic_data_offset = 0; /* avoid warning */
if (file_type != TCC_OUTPUT_OBJ) {
relocate_common_syms();
tcc_add_linker_symbols(s1);
if (!s1->static_link) {
const char *name;
int sym_index, index;
ElfW(Sym) *esym, *sym_end;
if (file_type == TCC_OUTPUT_EXE) {
char *ptr;
/* add interpreter section only if executable */
interp = new_section(s1, ".interp", SHT_PROGBITS, SHF_ALLOC);
interp->sh_addralign = 1;
ptr = section_ptr_add(interp, sizeof(elf_interp));
strcpy(ptr, elf_interp);
}
/* add dynamic symbol table */
s1->dynsym = new_symtab(s1, ".dynsym", SHT_DYNSYM, SHF_ALLOC,
".dynstr",
".hash", SHF_ALLOC);
dynstr = s1->dynsym->link;
/* add dynamic section */
dynamic = new_section(s1, ".dynamic", SHT_DYNAMIC,
SHF_ALLOC | SHF_WRITE);
dynamic->link = dynstr;
dynamic->sh_entsize = sizeof(ElfW(Dyn));
/* add PLT */
s1->plt = new_section(s1, ".plt", SHT_PROGBITS,
SHF_ALLOC | SHF_EXECINSTR);
s1->plt->sh_entsize = 4;
build_got(s1);
/* scan for undefined symbols and see if they are in the
dynamic symbols. If a symbol STT_FUNC is found, then we
add it in the PLT. If a symbol STT_OBJECT is found, we
add it in the .bss section with a suitable relocation */
sym_end = (ElfW(Sym) *)(symtab_section->data +
symtab_section->data_offset);
if (file_type == TCC_OUTPUT_EXE) {
for(sym = (ElfW(Sym) *)symtab_section->data + 1;
sym < sym_end;
sym++) {
if (sym->st_shndx == SHN_UNDEF) {
name = symtab_section->link->data + sym->st_name;
sym_index = find_elf_sym(s1->dynsymtab_section, name);
if (sym_index) {
esym = &((ElfW(Sym) *)s1->dynsymtab_section->data)[sym_index];
type = ELFW(ST_TYPE)(esym->st_info);
if (type == STT_FUNC) {
put_got_entry(s1, R_JMP_SLOT, esym->st_size,
esym->st_info,
sym - (ElfW(Sym) *)symtab_section->data);
} else if (type == STT_OBJECT) {
unsigned long offset;
offset = bss_section->data_offset;
/* XXX: which alignment ? */
offset = (offset + 16 - 1) & -16;
index = put_elf_sym(s1->dynsym, offset, esym->st_size,
esym->st_info, 0,
bss_section->sh_num, name);
put_elf_reloc(s1->dynsym, bss_section,
offset, R_COPY, index);
offset += esym->st_size;
bss_section->data_offset = offset;
}
} else {
/* STB_WEAK undefined symbols are accepted */
/* XXX: _fp_hw seems to be part of the ABI, so we ignore
it */
if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK ||
!strcmp(name, "_fp_hw")) {
} else {
error_noabort("undefined symbol '%s'", name);
}
}
} else if (s1->rdynamic &&
ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
/* if -rdynamic option, then export all non
local symbols */
name = symtab_section->link->data + sym->st_name;
put_elf_sym(s1->dynsym, sym->st_value, sym->st_size,
sym->st_info, 0,
sym->st_shndx, name);
}
}
if (s1->nb_errors)
goto fail;
/* now look at unresolved dynamic symbols and export
corresponding symbol */
sym_end = (ElfW(Sym) *)(s1->dynsymtab_section->data +
s1->dynsymtab_section->data_offset);
for(esym = (ElfW(Sym) *)s1->dynsymtab_section->data + 1;
esym < sym_end;
esym++) {
if (esym->st_shndx == SHN_UNDEF) {
name = s1->dynsymtab_section->link->data + esym->st_name;
sym_index = find_elf_sym(symtab_section, name);
if (sym_index) {
/* XXX: avoid adding a symbol if already
present because of -rdynamic ? */
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
put_elf_sym(s1->dynsym, sym->st_value, sym->st_size,
sym->st_info, 0,
sym->st_shndx, name);
} else {
if (ELFW(ST_BIND)(esym->st_info) == STB_WEAK) {
/* weak symbols can stay undefined */
} else {
warning("undefined dynamic symbol '%s'", name);
}
}
}
}
} else {
int nb_syms;
/* shared library case : we simply export all the global symbols */
nb_syms = symtab_section->data_offset / sizeof(ElfW(Sym));
s1->symtab_to_dynsym = tcc_mallocz(sizeof(int) * nb_syms);
for(sym = (ElfW(Sym) *)symtab_section->data + 1;
sym < sym_end;
sym++) {
if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
#if defined(TCC_OUTPUT_DLL_WITH_PLT)
if (ELFW(ST_TYPE)(sym->st_info) == STT_FUNC &&
sym->st_shndx == SHN_UNDEF) {
put_got_entry(s1, R_JMP_SLOT, sym->st_size,
sym->st_info,
sym - (ElfW(Sym) *)symtab_section->data);
}
else if (ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT) {
put_got_entry(s1, R_X86_64_GLOB_DAT, sym->st_size,
sym->st_info,
sym - (ElfW(Sym) *)symtab_section->data);
}
else
#endif
{
name = symtab_section->link->data + sym->st_name;
index = put_elf_sym(s1->dynsym, sym->st_value, sym->st_size,
sym->st_info, 0,
sym->st_shndx, name);
s1->symtab_to_dynsym[sym -
(ElfW(Sym) *)symtab_section->data] =
index;
}
}
}
}
build_got_entries(s1);
/* add a list of needed dlls */
for(i = 0; i < s1->nb_loaded_dlls; i++) {
DLLReference *dllref = s1->loaded_dlls[i];
if (dllref->level == 0)
put_dt(dynamic, DT_NEEDED, put_elf_str(dynstr, dllref->name));
}
/* XXX: currently, since we do not handle PIC code, we
must relocate the readonly segments */
if (file_type == TCC_OUTPUT_DLL) {
if (s1->soname)
put_dt(dynamic, DT_SONAME, put_elf_str(dynstr, s1->soname));
put_dt(dynamic, DT_TEXTREL, 0);
}
/* add necessary space for other entries */
saved_dynamic_data_offset = dynamic->data_offset;
dynamic->data_offset += sizeof(ElfW(Dyn)) * 9;
} else {
/* still need to build got entries in case of static link */
build_got_entries(s1);
}
}
memset(&ehdr, 0, sizeof(ehdr));
/* we add a section for symbols */
strsec = new_section(s1, ".shstrtab", SHT_STRTAB, 0);
put_elf_str(strsec, "");
/* compute number of sections */
shnum = s1->nb_sections;
/* this array is used to reorder sections in the output file */
section_order = tcc_malloc(sizeof(int) * shnum);
section_order[0] = 0;
sh_order_index = 1;
/* compute number of program headers */
switch(file_type) {
default:
case TCC_OUTPUT_OBJ:
phnum = 0;
break;
case TCC_OUTPUT_EXE:
if (!s1->static_link)
phnum = 4;
else
phnum = 2;
break;
case TCC_OUTPUT_DLL:
phnum = 3;
break;
}
/* allocate strings for section names and decide if an unallocated
section should be output */
/* NOTE: the strsec section comes last, so its size is also
correct ! */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
s->sh_name = put_elf_str(strsec, s->name);
#if 0 //gr
printf("section: f=%08x t=%08x i=%08x %s %s\n",
s->sh_flags,
s->sh_type,
s->sh_info,
s->name,
s->reloc ? s->reloc->name : "n"
);
#endif
/* when generating a DLL, we include relocations but we may
patch them */
if (file_type == TCC_OUTPUT_DLL &&
s->sh_type == SHT_RELX &&
!(s->sh_flags & SHF_ALLOC)) {
/* //gr: avoid bogus relocs for empty (debug) sections */
if (s1->sections[s->sh_info]->sh_flags & SHF_ALLOC)
prepare_dynamic_rel(s1, s);
else if (s1->do_debug)
s->sh_size = s->data_offset;
} else if (s1->do_debug ||
file_type == TCC_OUTPUT_OBJ ||
(s->sh_flags & SHF_ALLOC) ||
i == (s1->nb_sections - 1)) {
/* we output all sections if debug or object file */
s->sh_size = s->data_offset;
}
}
/* allocate program segment headers */
phdr = tcc_mallocz(phnum * sizeof(ElfW(Phdr)));
if (s1->output_format == TCC_OUTPUT_FORMAT_ELF) {
file_offset = sizeof(ElfW(Ehdr)) + phnum * sizeof(ElfW(Phdr));
} else {
file_offset = 0;
}
if (phnum > 0) {
/* compute section to program header mapping */
if (s1->has_text_addr) {
int a_offset, p_offset;
addr = s1->text_addr;
/* we ensure that (addr % ELF_PAGE_SIZE) == file_offset %
ELF_PAGE_SIZE */
a_offset = addr & (ELF_PAGE_SIZE - 1);
p_offset = file_offset & (ELF_PAGE_SIZE - 1);
if (a_offset < p_offset)
a_offset += ELF_PAGE_SIZE;
file_offset += (a_offset - p_offset);
} else {
if (file_type == TCC_OUTPUT_DLL)
addr = 0;
else
addr = ELF_START_ADDR;
/* compute address after headers */
addr += (file_offset & (ELF_PAGE_SIZE - 1));
}
/* dynamic relocation table information, for .dynamic section */
rel_size = 0;
rel_addr = 0;
/* leave one program header for the program interpreter */
ph = &phdr[0];
if (interp)
ph++;
for(j = 0; j < 2; j++) {
ph->p_type = PT_LOAD;
if (j == 0)
ph->p_flags = PF_R | PF_X;
else
ph->p_flags = PF_R | PF_W;
ph->p_align = ELF_PAGE_SIZE;
/* we do the following ordering: interp, symbol tables,
relocations, progbits, nobits */
/* XXX: do faster and simpler sorting */
for(k = 0; k < 5; k++) {
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
/* compute if section should be included */
if (j == 0) {
if ((s->sh_flags & (SHF_ALLOC | SHF_WRITE)) !=
SHF_ALLOC)
continue;
} else {
if ((s->sh_flags & (SHF_ALLOC | SHF_WRITE)) !=
(SHF_ALLOC | SHF_WRITE))
continue;
}
if (s == interp) {
if (k != 0)
continue;
} else if (s->sh_type == SHT_DYNSYM ||
s->sh_type == SHT_STRTAB ||
s->sh_type == SHT_HASH) {
if (k != 1)
continue;
} else if (s->sh_type == SHT_RELX) {
if (k != 2)
continue;
} else if (s->sh_type == SHT_NOBITS) {
if (k != 4)
continue;
} else {
if (k != 3)
continue;
}
section_order[sh_order_index++] = i;
/* section matches: we align it and add its size */
tmp = addr;
addr = (addr + s->sh_addralign - 1) &
~(s->sh_addralign - 1);
file_offset += addr - tmp;
s->sh_offset = file_offset;
s->sh_addr = addr;
/* update program header infos */
if (ph->p_offset == 0) {
ph->p_offset = file_offset;
ph->p_vaddr = addr;
ph->p_paddr = ph->p_vaddr;
}
/* update dynamic relocation infos */
if (s->sh_type == SHT_RELX) {
if (rel_size == 0)
rel_addr = addr;
rel_size += s->sh_size;
}
addr += s->sh_size;
if (s->sh_type != SHT_NOBITS)
file_offset += s->sh_size;
}
}
ph->p_filesz = file_offset - ph->p_offset;
ph->p_memsz = addr - ph->p_vaddr;
ph++;
if (j == 0) {
if (s1->output_format == TCC_OUTPUT_FORMAT_ELF) {
/* if in the middle of a page, we duplicate the page in
memory so that one copy is RX and the other is RW */
if ((addr & (ELF_PAGE_SIZE - 1)) != 0)
addr += ELF_PAGE_SIZE;
} else {
addr = (addr + ELF_PAGE_SIZE - 1) & ~(ELF_PAGE_SIZE - 1);
file_offset = (file_offset + ELF_PAGE_SIZE - 1) &
~(ELF_PAGE_SIZE - 1);
}
}
}
/* if interpreter, then add corresponing program header */
if (interp) {
ph = &phdr[0];
ph->p_type = PT_INTERP;
ph->p_offset = interp->sh_offset;
ph->p_vaddr = interp->sh_addr;
ph->p_paddr = ph->p_vaddr;
ph->p_filesz = interp->sh_size;
ph->p_memsz = interp->sh_size;
ph->p_flags = PF_R;
ph->p_align = interp->sh_addralign;
}
/* if dynamic section, then add corresponing program header */
if (dynamic) {
ElfW(Sym) *sym_end;
ph = &phdr[phnum - 1];
ph->p_type = PT_DYNAMIC;
ph->p_offset = dynamic->sh_offset;
ph->p_vaddr = dynamic->sh_addr;
ph->p_paddr = ph->p_vaddr;
ph->p_filesz = dynamic->sh_size;
ph->p_memsz = dynamic->sh_size;
ph->p_flags = PF_R | PF_W;
ph->p_align = dynamic->sh_addralign;
/* put GOT dynamic section address */
put32(s1->got->data, dynamic->sh_addr);
/* relocate the PLT */
if (file_type == TCC_OUTPUT_EXE
#if defined(TCC_OUTPUT_DLL_WITH_PLT)
|| file_type == TCC_OUTPUT_DLL
#endif
) {
uint8_t *p, *p_end;
p = s1->plt->data;
p_end = p + s1->plt->data_offset;
if (p < p_end) {
#if defined(TCC_TARGET_I386)
put32(p + 2, get32(p + 2) + s1->got->sh_addr);
put32(p + 8, get32(p + 8) + s1->got->sh_addr);
p += 16;
while (p < p_end) {
put32(p + 2, get32(p + 2) + s1->got->sh_addr);
p += 16;
}
#elif defined(TCC_TARGET_X86_64)
int x = s1->got->sh_addr - s1->plt->sh_addr - 6;
put32(p + 2, get32(p + 2) + x);
put32(p + 8, get32(p + 8) + x - 6);
p += 16;
while (p < p_end) {
put32(p + 2, get32(p + 2) + x + s1->plt->data - p);
p += 16;
}
#elif defined(TCC_TARGET_ARM)
int x;
x=s1->got->sh_addr - s1->plt->sh_addr - 12;
p +=16;
while (p < p_end) {
put32(p + 12, x + get32(p + 12) + s1->plt->data - p);
p += 16;
}
#elif defined(TCC_TARGET_C67)
/* XXX: TODO */
#else
#error unsupported CPU
#endif
}
}
/* relocate symbols in .dynsym */
sym_end = (ElfW(Sym) *)(s1->dynsym->data + s1->dynsym->data_offset);
for(sym = (ElfW(Sym) *)s1->dynsym->data + 1;
sym < sym_end;
sym++) {
if (sym->st_shndx == SHN_UNDEF) {
/* relocate to the PLT if the symbol corresponds
to a PLT entry */
if (sym->st_value)
sym->st_value += s1->plt->sh_addr;
} else if (sym->st_shndx < SHN_LORESERVE) {
/* do symbol relocation */
sym->st_value += s1->sections[sym->st_shndx]->sh_addr;
}
}
/* put dynamic section entries */
dynamic->data_offset = saved_dynamic_data_offset;
put_dt(dynamic, DT_HASH, s1->dynsym->hash->sh_addr);
put_dt(dynamic, DT_STRTAB, dynstr->sh_addr);
put_dt(dynamic, DT_SYMTAB, s1->dynsym->sh_addr);
put_dt(dynamic, DT_STRSZ, dynstr->data_offset);
put_dt(dynamic, DT_SYMENT, sizeof(ElfW(Sym)));
#ifdef TCC_TARGET_X86_64
put_dt(dynamic, DT_RELA, rel_addr);
put_dt(dynamic, DT_RELASZ, rel_size);
put_dt(dynamic, DT_RELAENT, sizeof(ElfW_Rel));
#else
put_dt(dynamic, DT_REL, rel_addr);
put_dt(dynamic, DT_RELSZ, rel_size);
put_dt(dynamic, DT_RELENT, sizeof(ElfW_Rel));
#endif
if (s1->do_debug)
put_dt(dynamic, DT_DEBUG, 0);
put_dt(dynamic, DT_NULL, 0);
}
ehdr.e_phentsize = sizeof(ElfW(Phdr));
ehdr.e_phnum = phnum;
ehdr.e_phoff = sizeof(ElfW(Ehdr));
}
/* all other sections come after */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (phnum > 0 && (s->sh_flags & SHF_ALLOC))
continue;
section_order[sh_order_index++] = i;
file_offset = (file_offset + s->sh_addralign - 1) &
~(s->sh_addralign - 1);
s->sh_offset = file_offset;
if (s->sh_type != SHT_NOBITS)
file_offset += s->sh_size;
}
/* if building executable or DLL, then relocate each section
except the GOT which is already relocated */
if (file_type != TCC_OUTPUT_OBJ) {
relocate_syms(s1, 0);
if (s1->nb_errors != 0) {
fail:
ret = -1;
goto the_end;
}
/* relocate sections */
/* XXX: ignore sections with allocated relocations ? */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (s->reloc && s != s1->got && (s->sh_flags & SHF_ALLOC)) //gr
relocate_section(s1, s);
}
/* relocate relocation entries if the relocation tables are
allocated in the executable */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if ((s->sh_flags & SHF_ALLOC) &&
s->sh_type == SHT_RELX) {
relocate_rel(s1, s);
}
}
/* get entry point address */
if (file_type == TCC_OUTPUT_EXE)
ehdr.e_entry = (unsigned long)tcc_get_symbol_err(s1, "_start");
else
ehdr.e_entry = text_section->sh_addr; /* XXX: is it correct ? */
}
/* write elf file */
if (file_type == TCC_OUTPUT_OBJ)
mode = 0666;
else
mode = 0777;
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, mode);
if (fd < 0) {
error_noabort("could not write '%s'", filename);
goto fail;
}
f = fdopen(fd, "wb");
if (s1->verbose)
printf("<- %s\n", filename);
#ifdef TCC_TARGET_COFF
if (s1->output_format == TCC_OUTPUT_FORMAT_COFF) {
tcc_output_coff(s1, f);
} else
#endif
if (s1->output_format == TCC_OUTPUT_FORMAT_ELF) {
sort_syms(s1, symtab_section);
/* align to 4 */
file_offset = (file_offset + 3) & -4;
/* fill header */
ehdr.e_ident[0] = ELFMAG0;
ehdr.e_ident[1] = ELFMAG1;
ehdr.e_ident[2] = ELFMAG2;
ehdr.e_ident[3] = ELFMAG3;
ehdr.e_ident[4] = TCC_ELFCLASS;
ehdr.e_ident[5] = ELFDATA2LSB;
ehdr.e_ident[6] = EV_CURRENT;
#ifdef __FreeBSD__
ehdr.e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
#endif
#ifdef TCC_TARGET_ARM
#ifdef TCC_ARM_EABI
ehdr.e_ident[EI_OSABI] = 0;
ehdr.e_flags = 4 << 24;
#else
ehdr.e_ident[EI_OSABI] = ELFOSABI_ARM;
#endif
#endif
switch(file_type) {
default:
case TCC_OUTPUT_EXE:
ehdr.e_type = ET_EXEC;
break;
case TCC_OUTPUT_DLL:
ehdr.e_type = ET_DYN;
break;
case TCC_OUTPUT_OBJ:
ehdr.e_type = ET_REL;
break;
}
ehdr.e_machine = EM_TCC_TARGET;
ehdr.e_version = EV_CURRENT;
ehdr.e_shoff = file_offset;
ehdr.e_ehsize = sizeof(ElfW(Ehdr));
ehdr.e_shentsize = sizeof(ElfW(Shdr));
ehdr.e_shnum = shnum;
ehdr.e_shstrndx = shnum - 1;
fwrite(&ehdr, 1, sizeof(ElfW(Ehdr)), f);
fwrite(phdr, 1, phnum * sizeof(ElfW(Phdr)), f);
offset = sizeof(ElfW(Ehdr)) + phnum * sizeof(ElfW(Phdr));
for(i=1;i<s1->nb_sections;i++) {
s = s1->sections[section_order[i]];
if (s->sh_type != SHT_NOBITS) {
while (offset < s->sh_offset) {
fputc(0, f);
offset++;
}
size = s->sh_size;
fwrite(s->data, 1, size, f);
offset += size;
}
}
/* output section headers */
while (offset < ehdr.e_shoff) {
fputc(0, f);
offset++;
}
for(i=0;i<s1->nb_sections;i++) {
sh = &shdr;
memset(sh, 0, sizeof(ElfW(Shdr)));
s = s1->sections[i];
if (s) {
sh->sh_name = s->sh_name;
sh->sh_type = s->sh_type;
sh->sh_flags = s->sh_flags;
sh->sh_entsize = s->sh_entsize;
sh->sh_info = s->sh_info;
if (s->link)
sh->sh_link = s->link->sh_num;
sh->sh_addralign = s->sh_addralign;
sh->sh_addr = s->sh_addr;
sh->sh_offset = s->sh_offset;
sh->sh_size = s->sh_size;
}
fwrite(sh, 1, sizeof(ElfW(Shdr)), f);
}
} else {
tcc_output_binary(s1, f, section_order);
}
fclose(f);
ret = 0;
the_end:
tcc_free(s1->symtab_to_dynsym);
tcc_free(section_order);
tcc_free(phdr);
tcc_free(s1->got_offsets);
return ret;
}
int tcc_output_file(TCCState *s, const char *filename)
{
int ret;
#ifdef TCC_TARGET_PE
if (s->output_type != TCC_OUTPUT_OBJ) {
ret = pe_output_file(s, filename);
} else
#endif
{
ret = elf_output_file(s, filename);
}
return ret;
}
static void *load_data(int fd, unsigned long file_offset, unsigned long size)
{
void *data;
data = tcc_malloc(size);
lseek(fd, file_offset, SEEK_SET);
read(fd, data, size);
return data;
}
typedef struct SectionMergeInfo {
Section *s; /* corresponding existing section */
unsigned long offset; /* offset of the new section in the existing section */
uint8_t new_section; /* true if section 's' was added */
uint8_t link_once; /* true if link once section */
} SectionMergeInfo;
/* load an object file and merge it with current files */
/* XXX: handle correctly stab (debug) info */
static int tcc_load_object_file(TCCState *s1,
int fd, unsigned long file_offset)
{
ElfW(Ehdr) ehdr;
ElfW(Shdr) *shdr, *sh;
int size, i, j, offset, offseti, nb_syms, sym_index, ret;
unsigned char *strsec, *strtab;
int *old_to_new_syms;
char *sh_name, *name;
SectionMergeInfo *sm_table, *sm;
ElfW(Sym) *sym, *symtab;
ElfW_Rel *rel, *rel_end;
Section *s;
int stab_index;
int stabstr_index;
stab_index = stabstr_index = 0;
if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr))
goto fail1;
if (ehdr.e_ident[0] != ELFMAG0 ||
ehdr.e_ident[1] != ELFMAG1 ||
ehdr.e_ident[2] != ELFMAG2 ||
ehdr.e_ident[3] != ELFMAG3)
goto fail1;
/* test if object file */
if (ehdr.e_type != ET_REL)
goto fail1;
/* test CPU specific stuff */
if (ehdr.e_ident[5] != ELFDATA2LSB ||
ehdr.e_machine != EM_TCC_TARGET) {
fail1:
error_noabort("invalid object file");
return -1;
}
/* read sections */
shdr = load_data(fd, file_offset + ehdr.e_shoff,
sizeof(ElfW(Shdr)) * ehdr.e_shnum);
sm_table = tcc_mallocz(sizeof(SectionMergeInfo) * ehdr.e_shnum);
/* load section names */
sh = &shdr[ehdr.e_shstrndx];
strsec = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
/* load symtab and strtab */
old_to_new_syms = NULL;
symtab = NULL;
strtab = NULL;
nb_syms = 0;
for(i = 1; i < ehdr.e_shnum; i++) {
sh = &shdr[i];
if (sh->sh_type == SHT_SYMTAB) {
if (symtab) {
error_noabort("object must contain only one symtab");
fail:
ret = -1;
goto the_end;
}
nb_syms = sh->sh_size / sizeof(ElfW(Sym));
symtab = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
sm_table[i].s = symtab_section;
/* now load strtab */
sh = &shdr[sh->sh_link];
strtab = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
}
}
/* now examine each section and try to merge its content with the
ones in memory */
for(i = 1; i < ehdr.e_shnum; i++) {
/* no need to examine section name strtab */
if (i == ehdr.e_shstrndx)
continue;
sh = &shdr[i];
sh_name = strsec + sh->sh_name;
/* ignore sections types we do not handle */
if (sh->sh_type != SHT_PROGBITS &&
sh->sh_type != SHT_RELX &&
#ifdef TCC_ARM_EABI
sh->sh_type != SHT_ARM_EXIDX &&
#endif
sh->sh_type != SHT_NOBITS &&
strcmp(sh_name, ".stabstr")
)
continue;
if (sh->sh_addralign < 1)
sh->sh_addralign = 1;
/* find corresponding section, if any */
for(j = 1; j < s1->nb_sections;j++) {
s = s1->sections[j];
if (!strcmp(s->name, sh_name)) {
if (!strncmp(sh_name, ".gnu.linkonce",
sizeof(".gnu.linkonce") - 1)) {
/* if a 'linkonce' section is already present, we
do not add it again. It is a little tricky as
symbols can still be defined in
it. */
sm_table[i].link_once = 1;
goto next;
} else {
goto found;
}
}
}
/* not found: create new section */
s = new_section(s1, sh_name, sh->sh_type, sh->sh_flags);
/* take as much info as possible from the section. sh_link and
sh_info will be updated later */
s->sh_addralign = sh->sh_addralign;
s->sh_entsize = sh->sh_entsize;
sm_table[i].new_section = 1;
found:
if (sh->sh_type != s->sh_type) {
error_noabort("invalid section type");
goto fail;
}
/* align start of section */
offset = s->data_offset;
if (0 == strcmp(sh_name, ".stab")) {
stab_index = i;
goto no_align;
}
if (0 == strcmp(sh_name, ".stabstr")) {
stabstr_index = i;
goto no_align;
}
size = sh->sh_addralign - 1;
offset = (offset + size) & ~size;
if (sh->sh_addralign > s->sh_addralign)
s->sh_addralign = sh->sh_addralign;
s->data_offset = offset;
no_align:
sm_table[i].offset = offset;
sm_table[i].s = s;
/* concatenate sections */
size = sh->sh_size;
if (sh->sh_type != SHT_NOBITS) {
unsigned char *ptr;
lseek(fd, file_offset + sh->sh_offset, SEEK_SET);
ptr = section_ptr_add(s, size);
read(fd, ptr, size);
} else {
s->data_offset += size;
}
next: ;
}
/* //gr relocate stab strings */
if (stab_index && stabstr_index) {
Stab_Sym *a, *b;
unsigned o;
s = sm_table[stab_index].s;
a = (Stab_Sym *)(s->data + sm_table[stab_index].offset);
b = (Stab_Sym *)(s->data + s->data_offset);
o = sm_table[stabstr_index].offset;
while (a < b)
a->n_strx += o, a++;
}
/* second short pass to update sh_link and sh_info fields of new
sections */
for(i = 1; i < ehdr.e_shnum; i++) {
s = sm_table[i].s;
if (!s || !sm_table[i].new_section)
continue;
sh = &shdr[i];
if (sh->sh_link > 0)
s->link = sm_table[sh->sh_link].s;
if (sh->sh_type == SHT_RELX) {
s->sh_info = sm_table[sh->sh_info].s->sh_num;
/* update backward link */
s1->sections[s->sh_info]->reloc = s;
}
}
sm = sm_table;
/* resolve symbols */
old_to_new_syms = tcc_mallocz(nb_syms * sizeof(int));
sym = symtab + 1;
for(i = 1; i < nb_syms; i++, sym++) {
if (sym->st_shndx != SHN_UNDEF &&
sym->st_shndx < SHN_LORESERVE) {
sm = &sm_table[sym->st_shndx];
if (sm->link_once) {
/* if a symbol is in a link once section, we use the
already defined symbol. It is very important to get
correct relocations */
if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
name = strtab + sym->st_name;
sym_index = find_elf_sym(symtab_section, name);
if (sym_index)
old_to_new_syms[i] = sym_index;
}
continue;
}
/* if no corresponding section added, no need to add symbol */
if (!sm->s)
continue;
/* convert section number */
sym->st_shndx = sm->s->sh_num;
/* offset value */
sym->st_value += sm->offset;
}
/* add symbol */
name = strtab + sym->st_name;
sym_index = add_elf_sym(symtab_section, sym->st_value, sym->st_size,
sym->st_info, sym->st_other,
sym->st_shndx, name);
old_to_new_syms[i] = sym_index;
}
/* third pass to patch relocation entries */
for(i = 1; i < ehdr.e_shnum; i++) {
s = sm_table[i].s;
if (!s)
continue;
sh = &shdr[i];
offset = sm_table[i].offset;
switch(s->sh_type) {
case SHT_RELX:
/* take relocation offset information */
offseti = sm_table[sh->sh_info].offset;
rel_end = (ElfW_Rel *)(s->data + s->data_offset);
for(rel = (ElfW_Rel *)(s->data + offset);
rel < rel_end;
rel++) {
int type;
unsigned sym_index;
/* convert symbol index */
type = ELFW(R_TYPE)(rel->r_info);
sym_index = ELFW(R_SYM)(rel->r_info);
/* NOTE: only one symtab assumed */
if (sym_index >= nb_syms)
goto invalid_reloc;
sym_index = old_to_new_syms[sym_index];
/* ignore link_once in rel section. */
if (!sym_index && !sm->link_once) {
invalid_reloc:
error_noabort("Invalid relocation entry [%2d] '%s' @ %.8x",
i, strsec + sh->sh_name, rel->r_offset);
goto fail;
}
rel->r_info = ELFW(R_INFO)(sym_index, type);
/* offset the relocation offset */
rel->r_offset += offseti;
}
break;
default:
break;
}
}
ret = 0;
the_end:
tcc_free(symtab);
tcc_free(strtab);
tcc_free(old_to_new_syms);
tcc_free(sm_table);
tcc_free(strsec);
tcc_free(shdr);
return ret;
}
#define ARMAG "!<arch>\012" /* For COFF and a.out archives */
typedef struct ArchiveHeader {
char ar_name[16]; /* name of this member */
char ar_date[12]; /* file mtime */
char ar_uid[6]; /* owner uid; printed as decimal */
char ar_gid[6]; /* owner gid; printed as decimal */
char ar_mode[8]; /* file mode, printed as octal */
char ar_size[10]; /* file size, printed as decimal */
char ar_fmag[2]; /* should contain ARFMAG */
} ArchiveHeader;
static int get_be32(const uint8_t *b)
{
return b[3] | (b[2] << 8) | (b[1] << 16) | (b[0] << 24);
}
/* load only the objects which resolve undefined symbols */
static int tcc_load_alacarte(TCCState *s1, int fd, int size)
{
int i, bound, nsyms, sym_index, off, ret;
uint8_t *data;
const char *ar_names, *p;
const uint8_t *ar_index;
ElfW(Sym) *sym;
data = tcc_malloc(size);
if (read(fd, data, size) != size)
goto fail;
nsyms = get_be32(data);
ar_index = data + 4;
ar_names = ar_index + nsyms * 4;
do {
bound = 0;
for(p = ar_names, i = 0; i < nsyms; i++, p += strlen(p)+1) {
sym_index = find_elf_sym(symtab_section, p);
if(sym_index) {
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
if(sym->st_shndx == SHN_UNDEF) {
off = get_be32(ar_index + i * 4) + sizeof(ArchiveHeader);
#if 0
printf("%5d\t%s\t%08x\n", i, p, sym->st_shndx);
#endif
++bound;
lseek(fd, off, SEEK_SET);
if(tcc_load_object_file(s1, fd, off) < 0) {
fail:
ret = -1;
goto the_end;
}
}
}
}
} while(bound);
ret = 0;
the_end:
tcc_free(data);
return ret;
}
/* load a '.a' file */
static int tcc_load_archive(TCCState *s1, int fd)
{
ArchiveHeader hdr;
char ar_size[11];
char ar_name[17];
char magic[8];
int size, len, i;
unsigned long file_offset;
/* skip magic which was already checked */
read(fd, magic, sizeof(magic));
for(;;) {
len = read(fd, &hdr, sizeof(hdr));
if (len == 0)
break;
if (len != sizeof(hdr)) {
error_noabort("invalid archive");
return -1;
}
memcpy(ar_size, hdr.ar_size, sizeof(hdr.ar_size));
ar_size[sizeof(hdr.ar_size)] = '\0';
size = strtol(ar_size, NULL, 0);
memcpy(ar_name, hdr.ar_name, sizeof(hdr.ar_name));
for(i = sizeof(hdr.ar_name) - 1; i >= 0; i--) {
if (ar_name[i] != ' ')
break;
}
ar_name[i + 1] = '\0';
// printf("name='%s' size=%d %s\n", ar_name, size, ar_size);
file_offset = lseek(fd, 0, SEEK_CUR);
/* align to even */
size = (size + 1) & ~1;
if (!strcmp(ar_name, "/")) {
/* coff symbol table : we handle it */
if(s1->alacarte_link)
return tcc_load_alacarte(s1, fd, size);
} else if (!strcmp(ar_name, "//") ||
!strcmp(ar_name, "__.SYMDEF") ||
!strcmp(ar_name, "__.SYMDEF/") ||
!strcmp(ar_name, "ARFILENAMES/")) {
/* skip symbol table or archive names */
} else {
if (tcc_load_object_file(s1, fd, file_offset) < 0)
return -1;
}
lseek(fd, file_offset + size, SEEK_SET);
}
return 0;
}
/* load a DLL and all referenced DLLs. 'level = 0' means that the DLL
is referenced by the user (so it should be added as DT_NEEDED in
the generated ELF file) */
static int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level)
{
ElfW(Ehdr) ehdr;
ElfW(Shdr) *shdr, *sh, *sh1;
int i, j, nb_syms, nb_dts, sym_bind, ret;
ElfW(Sym) *sym, *dynsym;
ElfW(Dyn) *dt, *dynamic;
unsigned char *dynstr;
const char *name, *soname;
DLLReference *dllref;
read(fd, &ehdr, sizeof(ehdr));
/* test CPU specific stuff */
if (ehdr.e_ident[5] != ELFDATA2LSB ||
ehdr.e_machine != EM_TCC_TARGET) {
error_noabort("bad architecture");
return -1;
}
/* read sections */
shdr = load_data(fd, ehdr.e_shoff, sizeof(ElfW(Shdr)) * ehdr.e_shnum);
/* load dynamic section and dynamic symbols */
nb_syms = 0;
nb_dts = 0;
dynamic = NULL;
dynsym = NULL; /* avoid warning */
dynstr = NULL; /* avoid warning */
for(i = 0, sh = shdr; i < ehdr.e_shnum; i++, sh++) {
switch(sh->sh_type) {
case SHT_DYNAMIC:
nb_dts = sh->sh_size / sizeof(ElfW(Dyn));
dynamic = load_data(fd, sh->sh_offset, sh->sh_size);
break;
case SHT_DYNSYM:
nb_syms = sh->sh_size / sizeof(ElfW(Sym));
dynsym = load_data(fd, sh->sh_offset, sh->sh_size);
sh1 = &shdr[sh->sh_link];
dynstr = load_data(fd, sh1->sh_offset, sh1->sh_size);
break;
default:
break;
}
}
/* compute the real library name */
soname = tcc_basename(filename);
for(i = 0, dt = dynamic; i < nb_dts; i++, dt++) {
if (dt->d_tag == DT_SONAME) {
soname = dynstr + dt->d_un.d_val;
}
}
/* if the dll is already loaded, do not load it */
for(i = 0; i < s1->nb_loaded_dlls; i++) {
dllref = s1->loaded_dlls[i];
if (!strcmp(soname, dllref->name)) {
/* but update level if needed */
if (level < dllref->level)
dllref->level = level;
ret = 0;
goto the_end;
}
}
// printf("loading dll '%s'\n", soname);
/* add the dll and its level */
dllref = tcc_mallocz(sizeof(DLLReference) + strlen(soname));
dllref->level = level;
strcpy(dllref->name, soname);
dynarray_add((void ***)&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
/* add dynamic symbols in dynsym_section */
for(i = 1, sym = dynsym + 1; i < nb_syms; i++, sym++) {
sym_bind = ELFW(ST_BIND)(sym->st_info);
if (sym_bind == STB_LOCAL)
continue;
name = dynstr + sym->st_name;
add_elf_sym(s1->dynsymtab_section, sym->st_value, sym->st_size,
sym->st_info, sym->st_other, sym->st_shndx, name);
}
/* load all referenced DLLs */
for(i = 0, dt = dynamic; i < nb_dts; i++, dt++) {
switch(dt->d_tag) {
case DT_NEEDED:
name = dynstr + dt->d_un.d_val;
for(j = 0; j < s1->nb_loaded_dlls; j++) {
dllref = s1->loaded_dlls[j];
if (!strcmp(name, dllref->name))
goto already_loaded;
}
if (tcc_add_dll(s1, name, AFF_REFERENCED_DLL) < 0) {
error_noabort("referenced dll '%s' not found", name);
ret = -1;
goto the_end;
}
already_loaded:
break;
}
}
ret = 0;
the_end:
tcc_free(dynstr);
tcc_free(dynsym);
tcc_free(dynamic);
tcc_free(shdr);
return ret;
}
#define LD_TOK_NAME 256
#define LD_TOK_EOF (-1)
/* return next ld script token */
static int ld_next(TCCState *s1, char *name, int name_size)
{
int c;
char *q;
redo:
switch(ch) {
case ' ':
case '\t':
case '\f':
case '\v':
case '\r':
case '\n':
inp();
goto redo;
case '/':
minp();
if (ch == '*') {
file->buf_ptr = parse_comment(file->buf_ptr);
ch = file->buf_ptr[0];
goto redo;
} else {
q = name;
*q++ = '/';
goto parse_name;
}
break;
/* case 'a' ... 'z': */
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
/* case 'A' ... 'z': */
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case '\\':
case '.':
case '$':
case '~':
q = name;
parse_name:
for(;;) {
if (!((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
strchr("/.-_+=$:\\,~", ch)))
break;
if ((q - name) < name_size - 1) {
*q++ = ch;
}
minp();
}
*q = '\0';
c = LD_TOK_NAME;
break;
case CH_EOF:
c = LD_TOK_EOF;
break;
default:
c = ch;
inp();
break;
}
#if 0
printf("tok=%c %d\n", c, c);
if (c == LD_TOK_NAME)
printf(" name=%s\n", name);
#endif
return c;
}
static int ld_add_file_list(TCCState *s1, int as_needed)
{
char filename[1024];
int t, ret;
t = ld_next(s1, filename, sizeof(filename));
if (t != '(')
expect("(");
t = ld_next(s1, filename, sizeof(filename));
for(;;) {
if (t == LD_TOK_EOF) {
error_noabort("unexpected end of file");
return -1;
} else if (t == ')') {
break;
} else if (t != LD_TOK_NAME) {
error_noabort("filename expected");
return -1;
}
if (!strcmp(filename, "AS_NEEDED")) {
ret = ld_add_file_list(s1, 1);
if (ret)
return ret;
} else {
/* TODO: Implement AS_NEEDED support. Ignore it for now */
if (!as_needed)
tcc_add_file(s1, filename);
}
t = ld_next(s1, filename, sizeof(filename));
if (t == ',') {
t = ld_next(s1, filename, sizeof(filename));
}
}
return 0;
}
/* interpret a subset of GNU ldscripts to handle the dummy libc.so
files */
static int tcc_load_ldscript(TCCState *s1)
{
char cmd[64];
char filename[1024];
int t, ret;
ch = file->buf_ptr[0];
ch = handle_eob();
for(;;) {
t = ld_next(s1, cmd, sizeof(cmd));
if (t == LD_TOK_EOF)
return 0;
else if (t != LD_TOK_NAME)
return -1;
if (!strcmp(cmd, "INPUT") ||
!strcmp(cmd, "GROUP")) {
ret = ld_add_file_list(s1, 0);
if (ret)
return ret;
} else if (!strcmp(cmd, "OUTPUT_FORMAT") ||
!strcmp(cmd, "TARGET")) {
/* ignore some commands */
t = ld_next(s1, cmd, sizeof(cmd));
if (t != '(')
expect("(");
for(;;) {
t = ld_next(s1, filename, sizeof(filename));
if (t == LD_TOK_EOF) {
error_noabort("unexpected end of file");
return -1;
} else if (t == ')') {
break;
}
}
} else {
return -1;
}
}
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/tccelf.c | C | lgpl | 90,590 |
#! /usr/local/bin/tcc -run
#include <tcclib.h>
int main()
{
printf("Hello World\n");
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/ex1.c | C | lgpl | 106 |
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/ex5.c | C | lgpl | 98 |
#! /usr/local/bin/tcc -run
#include <tcclib.h>
int main()
{
printf("Hello World\n");
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/.svn/text-base/ex1.c.svn-base | C | lgpl | 106 |
#!./tcc -run -L/usr/X11R6/lib -lX11
#include <stdlib.h>
#include <stdio.h>
#include <X11/Xlib.h>
/* Yes, TCC can use X11 too ! */
int main(int argc, char **argv)
{
Display *display;
Screen *screen;
display = XOpenDisplay("");
if (!display) {
fprintf(stderr, "Could not open X11 display\n");
exit(1);
}
printf("X11 display opened.\n");
screen = XScreenOfDisplay(display, 0);
printf("width = %d\nheight = %d\ndepth = %d\n",
screen->width,
screen->height,
screen->root_depth);
XCloseDisplay(display);
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/.svn/text-base/ex4.c.svn-base | C | lgpl | 602 |
#include <stdlib.h>
#include <stdio.h>
#define N 20
int nb_num;
int tab[N];
int stack_ptr;
int stack_op[N];
int stack_res[60];
int result;
int find(int n, int i1, int a, int b, int op)
{
int i, j;
int c;
if (stack_ptr >= 0) {
stack_res[3*stack_ptr] = a;
stack_op[stack_ptr] = op;
stack_res[3*stack_ptr+1] = b;
stack_res[3*stack_ptr+2] = n;
if (n == result)
return 1;
tab[i1] = n;
}
for(i=0;i<nb_num;i++) {
for(j=i+1;j<nb_num;j++) {
a = tab[i];
b = tab[j];
if (a != 0 && b != 0) {
tab[j] = 0;
stack_ptr++;
if (find(a + b, i, a, b, '+'))
return 1;
if (find(a - b, i, a, b, '-'))
return 1;
if (find(b - a, i, b, a, '-'))
return 1;
if (find(a * b, i, a, b, '*'))
return 1;
if (b != 0) {
c = a / b;
if (find(c, i, a, b, '/'))
return 1;
}
if (a != 0) {
c = b / a;
if (find(c, i, b, a, '/'))
return 1;
}
stack_ptr--;
tab[i] = a;
tab[j] = b;
}
}
}
return 0;
}
int main(int argc, char **argv)
{
int i, res, p;
if (argc < 3) {
printf("usage: %s: result numbers...\n"
"Try to find result from numbers with the 4 basic operations.\n", argv[0]);
exit(1);
}
p = 1;
result = atoi(argv[p]);
printf("result=%d\n", result);
nb_num = 0;
for(i=p+1;i<argc;i++) {
tab[nb_num++] = atoi(argv[i]);
}
stack_ptr = -1;
res = find(0, 0, 0, 0, ' ');
if (res) {
for(i=0;i<=stack_ptr;i++) {
printf("%d %c %d = %d\n",
stack_res[3*i], stack_op[i],
stack_res[3*i+1], stack_res[3*i+2]);
}
return 0;
} else {
printf("Impossible\n");
return 1;
}
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/ex2.c | C | lgpl | 2,177 |
#!./tcc -run -L/usr/X11R6/lib -lX11
#include <stdlib.h>
#include <stdio.h>
#include <X11/Xlib.h>
/* Yes, TCC can use X11 too ! */
int main(int argc, char **argv)
{
Display *display;
Screen *screen;
display = XOpenDisplay("");
if (!display) {
fprintf(stderr, "Could not open X11 display\n");
exit(1);
}
printf("X11 display opened.\n");
screen = XScreenOfDisplay(display, 0);
printf("width = %d\nheight = %d\ndepth = %d\n",
screen->width,
screen->height,
screen->root_depth);
XCloseDisplay(display);
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/ex4.c | C | lgpl | 602 |
#include <stdlib.h>
#include <stdio.h>
int fib(n)
{
if (n <= 2)
return 1;
else
return fib(n-1) + fib(n-2);
}
int main(int argc, char **argv)
{
int n;
if (argc < 2) {
printf("usage: fib n\n"
"Compute nth Fibonacci number\n");
return 1;
}
n = atoi(argv[1]);
printf("fib(%d) = %d\n", n, fib(n, 2));
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/examples/ex3.c | C | lgpl | 390 |
#ifndef LIBTCC_H
#define LIBTCC_H
#ifdef LIBTCC_AS_DLL
#define LIBTCCAPI __declspec(dllexport)
#else
#define LIBTCCAPI
#endif
#ifdef __cplusplus
extern "C" {
#endif
struct TCCState;
typedef struct TCCState TCCState;
/* create a new TCC compilation context */
LIBTCCAPI TCCState *tcc_new(void);
/* free a TCC compilation context */
LIBTCCAPI void tcc_delete(TCCState *s);
/* add debug information in the generated code */
LIBTCCAPI void tcc_enable_debug(TCCState *s);
/* set error/warning display callback */
LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
void (*error_func)(void *opaque, const char *msg));
/* set/reset a warning */
LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value);
/*****************************/
/* preprocessor */
/* add include path */
LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname);
/* add in system include path */
LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname);
/* define preprocessor symbol 'sym'. Can put optional value */
LIBTCCAPI void tcc_define_symbol(TCCState *s, const char *sym, const char *value);
/* undefine preprocess symbol 'sym' */
LIBTCCAPI void tcc_undefine_symbol(TCCState *s, const char *sym);
/*****************************/
/* compiling */
/* add a file (either a C file, dll, an object, a library or an ld
script). Return -1 if error. */
LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename);
/* compile a string containing a C source. Return non zero if
error. */
LIBTCCAPI int tcc_compile_string(TCCState *s, const char *buf);
/*****************************/
/* linking commands */
/* set output type. MUST BE CALLED before any compilation */
#define TCC_OUTPUT_MEMORY 0 /* output will be ran in memory (no
output file) (default) */
#define TCC_OUTPUT_EXE 1 /* executable file */
#define TCC_OUTPUT_DLL 2 /* dynamic library */
#define TCC_OUTPUT_OBJ 3 /* object file */
#define TCC_OUTPUT_PREPROCESS 4 /* preprocessed file (used internally) */
LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type);
#define TCC_OUTPUT_FORMAT_ELF 0 /* default output format: ELF */
#define TCC_OUTPUT_FORMAT_BINARY 1 /* binary image output */
#define TCC_OUTPUT_FORMAT_COFF 2 /* COFF */
/* equivalent to -Lpath option */
LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname);
/* the library name is the same as the argument of the '-l' option */
LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname);
/* add a symbol to the compiled program */
LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, void *val);
/* output an executable, library or object file. DO NOT call
tcc_relocate() before. */
LIBTCCAPI int tcc_output_file(TCCState *s, const char *filename);
/* link and run main() function and return its value. DO NOT call
tcc_relocate() before. */
LIBTCCAPI int tcc_run(TCCState *s, int argc, char **argv);
/* copy code into memory passed in by the caller and do all relocations
(needed before using tcc_get_symbol()).
returns -1 on error and required size if ptr is NULL */
LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr);
/* return symbol value or NULL if not found */
LIBTCCAPI void *tcc_get_symbol(TCCState *s, const char *name);
/* set CONFIG_TCCDIR at runtime */
LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path);
#ifdef __cplusplus
}
#endif
#endif
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/libtcc.h | C | lgpl | 3,490 |
#
# Tiny C Compiler Makefile
#
TOP ?= .
include $(TOP)/config.mak
CFLAGS+=-g -Wall
CFLAGS_P=$(CFLAGS) -pg -static -DCONFIG_TCC_STATIC
LIBS_P=
ifneq ($(GCC_MAJOR),2)
CFLAGS+=-fno-strict-aliasing
endif
ifeq ($(ARCH),i386)
CFLAGS+=-mpreferred-stack-boundary=2
ifeq ($(GCC_MAJOR),2)
CFLAGS+=-m386 -malign-functions=0
else
CFLAGS+=-march=i386 -falign-functions=0
ifneq ($(GCC_MAJOR),3)
CFLAGS+=-Wno-pointer-sign -Wno-sign-compare -D_FORTIFY_SOURCE=0
endif
endif
endif
ifeq ($(ARCH),x86-64)
CFLAGS+=-Wno-pointer-sign
endif
ifndef CONFIG_WIN32
LIBS=-lm
ifndef CONFIG_NOLDL
LIBS+=-ldl
endif
endif
ifdef CONFIG_WIN32
NATIVE_TARGET=-DTCC_TARGET_PE
LIBTCC1=libtcc1.a
else
ifeq ($(ARCH),i386)
NATIVE_TARGET=-DTCC_TARGET_I386
LIBTCC1=libtcc1.a
BCHECK_O=bcheck.o
else
ifeq ($(ARCH),arm)
NATIVE_TARGET=-DTCC_TARGET_ARM
NATIVE_TARGET+=$(if $(wildcard /lib/ld-linux.so.3),-DTCC_ARM_EABI)
NATIVE_TARGET+=$(if $(shell grep -l "^Features.* \(vfp\|iwmmxt\) " /proc/cpuinfo),-DTCC_ARM_VFP)
else
ifeq ($(ARCH),x86-64)
NATIVE_TARGET=-DTCC_TARGET_X86_64
LIBTCC1=libtcc1.a
endif
endif
endif
endif
ifneq ($(wildcard /lib/ld-uClibc.so.0),)
NATIVE_TARGET+=-DTCC_UCLIBC
BCHECK_O=
endif
ifdef CONFIG_USE_LIBGCC
LIBTCC1=
endif
ifeq ($(TOP),.)
PROGS=tcc$(EXESUF)
I386_CROSS = i386-tcc$(EXESUF)
WIN32_CROSS = i386-win32-tcc$(EXESUF)
X64_CROSS = x86_64-tcc$(EXESUF)
ARM_CROSS = arm-tcc-fpa$(EXESUF) arm-tcc-fpa-ld$(EXESUF) \
arm-tcc-vfp$(EXESUF) arm-tcc-vfp-eabi$(EXESUF)
C67_CROSS = c67-tcc$(EXESUF)
CORE_FILES = tcc.c libtcc.c tccpp.c tccgen.c tccelf.c tccasm.c \
tcc.h config.h libtcc.h tcctok.h
I386_FILES = $(CORE_FILES) i386-gen.c i386-asm.c i386-asm.h
WIN32_FILES = $(CORE_FILES) i386-gen.c i386-asm.c i386-asm.h tccpe.c
X86_64_FILES = $(CORE_FILES) x86_64-gen.c
ARM_FILES = $(CORE_FILES) arm-gen.c
C67_FILES = $(CORE_FILES) c67-gen.c tcccoff.c
ifdef CONFIG_WIN32
PROGS+=tiny_impdef$(EXESUF) tiny_libmaker$(EXESUF)
NATIVE_FILES=$(WIN32_FILES)
PROGS_CROSS=$(I386_CROSS) $(X64_CROSS) $(ARM_CROSS) $(C67_CROSS)
else
ifeq ($(ARCH),i386)
NATIVE_FILES=$(I386_FILES)
PROGS_CROSS=$(X64_CROSS) $(WIN32_CROSS) $(ARM_CROSS) $(C67_CROSS)
else
ifeq ($(ARCH),x86-64)
NATIVE_FILES=$(X86_64_FILES)
PROGS_CROSS=$(I386_CROSS) $(WIN32_CROSS) $(ARM_CROSS) $(C67_CROSS)
else
ifeq ($(ARCH),arm)
NATIVE_FILES=$(ARM_FILES)
PROGS_CROSS=$(I386_CROSS) $(X64_CROSS) $(WIN32_CROSS) $(C67_CROSS)
endif
endif
endif
endif
ifdef CONFIG_CROSS
PROGS+=$(PROGS_CROSS)
endif
all: $(PROGS) $(LIBTCC1) $(BCHECK_O) libtcc.a tcc-doc.html tcc.1 libtcc_test$(EXESUF)
# Host Tiny C Compiler
tcc$(EXESUF): $(NATIVE_FILES)
$(CC) -o $@ $< $(NATIVE_TARGET) $(CFLAGS) $(LIBS)
# Cross Tiny C Compilers
i386-tcc$(EXESUF): $(I386_FILES)
$(CC) -o $@ $< -DTCC_TARGET_I386 $(CFLAGS) $(LIBS)
i386-win32-tcc$(EXESUF): $(WIN32_FILES)
$(CC) -o $@ $< -DTCC_TARGET_PE $(CFLAGS) $(LIBS)
x86_64-tcc$(EXESUF): $(X86_64_FILES)
$(CC) -o $@ $< -DTCC_TARGET_X86_64 $(CFLAGS) $(LIBS)
c67-tcc$(EXESUF): $(C67_FILES)
$(CC) -o $@ $< -DTCC_TARGET_C67 $(CFLAGS) $(LIBS)
arm-tcc-fpa$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM $(CFLAGS) $(LIBS)
arm-tcc-fpa-ld$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DLDOUBLE_SIZE=12 $(CFLAGS) $(LIBS)
arm-tcc-vfp$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DTCC_ARM_VFP $(CFLAGS) $(LIBS)
arm-tcc-vfp-eabi$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DTCC_ARM_EABI $(CFLAGS) $(LIBS)
# libtcc generation and test
libtcc.o: $(NATIVE_FILES)
$(CC) -o $@ -c libtcc.c $(NATIVE_TARGET) $(CFLAGS)
libtcc.a: libtcc.o
$(AR) rcs $@ $^
libtcc_test$(EXESUF): tests/libtcc_test.c libtcc.a
$(CC) -o $@ $^ -I. $(CFLAGS) $(LIBS)
libtest: libtcc_test$(EXESUF) $(LIBTCC1)
./libtcc_test$(EXESUF) lib_path=.
# profiling version
tcc_p$(EXESUF): $(NATIVE_FILES)
$(CC) -o $@ $< $(NATIVE_TARGET) $(CFLAGS_P) $(LIBS_P)
# windows utilities
tiny_impdef$(EXESUF): win32/tools/tiny_impdef.c
$(CC) -o $@ $< $(CFLAGS)
tiny_libmaker$(EXESUF): win32/tools/tiny_libmaker.c
$(CC) -o $@ $< $(CFLAGS)
# TinyCC runtime libraries
LIBTCC1_OBJS=libtcc1.o
LIBTCC1_CC=$(CC)
VPATH+=lib
ifdef CONFIG_WIN32
# for windows, we must use TCC because we generate ELF objects
LIBTCC1_OBJS+=crt1.o wincrt1.o dllcrt1.o dllmain.o chkstk.o
LIBTCC1_CC=./tcc.exe -Bwin32 -DTCC_TARGET_PE
VPATH+=win32/lib
endif
ifeq ($(ARCH),i386)
LIBTCC1_OBJS+=alloca86.o alloca86-bt.o
endif
%.o: %.c
$(LIBTCC1_CC) -o $@ -c $< -O2 -Wall
%.o: %.S
$(LIBTCC1_CC) -o $@ -c $<
libtcc1.a: $(LIBTCC1_OBJS)
$(AR) rcs $@ $^
bcheck.o: bcheck.c
$(CC) -o $@ -c $< -O2 -Wall
# install
TCC_INCLUDES = stdarg.h stddef.h stdbool.h float.h varargs.h tcclib.h
INSTALL=install
ifndef CONFIG_WIN32
install: $(PROGS) $(LIBTCC1) $(BCHECK_O) libtcc.a tcc.1 tcc-doc.html
mkdir -p "$(bindir)"
$(INSTALL) -s -m755 $(PROGS) "$(bindir)"
mkdir -p "$(mandir)/man1"
$(INSTALL) tcc.1 "$(mandir)/man1"
mkdir -p "$(tccdir)"
mkdir -p "$(tccdir)/include"
ifneq ($(LIBTCC1),)
$(INSTALL) -m644 $(LIBTCC1) "$(tccdir)"
endif
ifneq ($(BCHECK_O),)
$(INSTALL) -m644 $(BCHECK_O) "$(tccdir)"
endif
$(INSTALL) -m644 $(addprefix include/,$(TCC_INCLUDES)) "$(tccdir)/include"
mkdir -p "$(docdir)"
$(INSTALL) -m644 tcc-doc.html "$(docdir)"
mkdir -p "$(libdir)"
$(INSTALL) -m644 libtcc.a "$(libdir)"
mkdir -p "$(includedir)"
$(INSTALL) -m644 libtcc.h "$(includedir)"
uninstall:
rm -fv $(foreach P,$(PROGS),"$(bindir)/$P")
rm -fv $(foreach P,$(LIBTCC1) $(BCHECK_O),"$(tccdir)/$P")
rm -fv $(foreach P,$(TCC_INCLUDES),"$(tccdir)/include/$P")
rm -fv "$(docdir)/tcc-doc.html" "$(mandir)/man1/tcc.1"
rm -fv "$(libdir)/libtcc.a" "$(includedir)/libtcc.h"
else
install: $(PROGS) $(LIBTCC1) libtcc.a tcc-doc.html
mkdir -p "$(tccdir)"
mkdir -p "$(tccdir)/lib"
mkdir -p "$(tccdir)/include"
mkdir -p "$(tccdir)/examples"
mkdir -p "$(tccdir)/doc"
mkdir -p "$(tccdir)/libtcc"
$(INSTALL) -s -m755 $(PROGS) "$(tccdir)"
$(INSTALL) -m644 $(LIBTCC1) win32/lib/*.def "$(tccdir)/lib"
cp -r win32/include/. "$(tccdir)/include"
cp -r win32/examples/. "$(tccdir)/examples"
# $(INSTALL) -m644 $(addprefix include/,$(TCC_INCLUDES)) "$(tccdir)/include"
$(INSTALL) -m644 tcc-doc.html win32/tcc-win32.txt "$(tccdir)/doc"
$(INSTALL) -m644 libtcc.a libtcc.h "$(tccdir)/libtcc"
endif
# documentation and man page
tcc-doc.html: tcc-doc.texi
-texi2html -monolithic -number $<
tcc.1: tcc-doc.texi
-./texi2pod.pl $< tcc.pod
-pod2man --section=1 --center=" " --release=" " tcc.pod > $@
# tar release (use 'make -k tar' on a checkouted tree)
TCC-VERSION=tcc-$(shell cat VERSION)
tar:
rm -rf /tmp/$(TCC-VERSION)
cp -r . /tmp/$(TCC-VERSION)
( cd /tmp ; tar zcvf ~/$(TCC-VERSION).tar.gz $(TCC-VERSION) --exclude CVS )
rm -rf /tmp/$(TCC-VERSION)
# in tests subdir
test clean :
$(MAKE) -C tests $@
# clean
clean: local_clean
local_clean:
rm -vf $(PROGS) tcc_p$(EXESUF) tcc.pod *~ *.o *.a *.out libtcc_test$(EXESUF)
distclean: clean
rm -vf config.h config.mak config.texi tcc.1 tcc-doc.html
endif # ifeq ($(TOP),.)
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/Makefile | Makefile | lgpl | 6,940 |
/*
* This program is for making libtcc1.a without ar
* tiny_libmaker - tiny elf lib maker
* usage: tiny_libmaker [lib] files...
* Copyright (c) 2007 Timppa
*
* This program is free software but WITHOUT ANY WARRANTY
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h> /* for mktemp */
#endif
/* #include "ar-elf.h" */
/* "ar-elf.h" */
/* ELF_v1.2.pdf */
typedef unsigned short int Elf32_Half;
typedef int Elf32_Sword;
typedef unsigned int Elf32_Word;
typedef unsigned int Elf32_Addr;
typedef unsigned int Elf32_Off;
typedef unsigned short int Elf32_Section;
#define EI_NIDENT 16
typedef struct {
unsigned char e_ident[EI_NIDENT];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
} Elf32_Ehdr;
typedef struct {
Elf32_Word sh_name;
Elf32_Word sh_type;
Elf32_Word sh_flags;
Elf32_Addr sh_addr;
Elf32_Off sh_offset;
Elf32_Word sh_size;
Elf32_Word sh_link;
Elf32_Word sh_info;
Elf32_Word sh_addralign;
Elf32_Word sh_entsize;
} Elf32_Shdr;
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
typedef struct {
Elf32_Word st_name;
Elf32_Addr st_value;
Elf32_Word st_size;
unsigned char st_info;
unsigned char st_other;
Elf32_Half st_shndx;
} Elf32_Sym;
#define ELF32_ST_BIND(i) ((i)>>4)
#define ELF32_ST_TYPE(i) ((i)&0xf)
#define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf))
#define STT_NOTYPE 0
#define STT_OBJECT 1
#define STT_FUNC 2
#define STT_SECTION 3
#define STT_FILE 4
#define STT_LOPROC 13
#define STT_HIPROC 15
#define STB_LOCAL 0
#define STB_GLOBAL 1
#define STB_WEAK 2
#define STB_LOPROC 13
#define STB_HIPROC 15
typedef struct {
Elf32_Word p_type;
Elf32_Off p_offset;
Elf32_Addr p_vaddr;
Elf32_Addr p_paddr;
Elf32_Word p_filesz;
Elf32_Word p_memsz;
Elf32_Word p_flags;
Elf32_Word p_align;
} Elf32_Phdr;
/* "ar-elf.h" ends */
#define ARMAG "!<arch>\n"
#define ARFMAG "`\n"
typedef struct ArHdr {
char ar_name[16];
char ar_date[12];
char ar_uid[6];
char ar_gid[6];
char ar_mode[8];
char ar_size[10];
char ar_fmag[2];
} ArHdr;
unsigned long le2belong(unsigned long ul) {
return ((ul & 0xFF0000)>>8)+((ul & 0xFF000000)>>24) +
((ul & 0xFF)<<24)+((ul & 0xFF00)<<8);
}
ArHdr arhdr = {
"/ ",
" ",
"0 ",
"0 ",
"0 ",
" ",
ARFMAG
};
ArHdr arhdro = {
" ",
" ",
"0 ",
"0 ",
"0 ",
" ",
ARFMAG
};
int main(int argc, char **argv)
{
FILE *fi, *fh, *fo;
Elf32_Ehdr *ehdr;
Elf32_Shdr *shdr;
Elf32_Sym *sym;
int i, fsize, iarg;
char *buf, *shstr, *symtab = NULL, *strtab = NULL;
int symtabsize = 0, strtabsize = 0;
char *anames = NULL;
int *afpos = NULL;
int istrlen, strpos = 0, fpos = 0, funccnt = 0, funcmax, hofs;
char afile[260], tfile[260], stmp[20];
strcpy(afile, "ar_test.a");
iarg = 1;
if (argc < 2)
{
printf("usage: tiny_libmaker [lib] file...\n");
return 1;
}
for (i=1; i<argc; i++) {
istrlen = strlen(argv[i]);
if (argv[i][istrlen-2] == '.') {
if(argv[i][istrlen-1] == 'a')
strcpy(afile, argv[i]);
else if(argv[i][istrlen-1] == 'o') {
iarg = i;
break;
}
}
}
strcpy(tfile, "./XXXXXX");
if (!mktemp(tfile) || (fo = fopen(tfile, "wb+")) == NULL)
{
fprintf(stderr, "Can't open temporary file %s\n", tfile);
return 2;
}
if ((fh = fopen(afile, "wb")) == NULL)
{
fprintf(stderr, "Can't open file %s \n", afile);
remove(tfile);
return 2;
}
funcmax = 250;
afpos = realloc(NULL, funcmax * sizeof *afpos); // 250 func
memcpy(&arhdro.ar_mode, "100666", 6);
//iarg = 1;
while (iarg < argc)
{
if (!strcmp(argv[iarg], "rcs")) {
iarg++;
continue;
}
if ((fi = fopen(argv[iarg], "rb")) == NULL)
{
fprintf(stderr, "Can't open file %s \n", argv[iarg]);
remove(tfile);
return 2;
}
fseek(fi, 0, SEEK_END);
fsize = ftell(fi);
fseek(fi, 0, SEEK_SET);
buf = malloc(fsize + 1);
fread(buf, fsize, 1, fi);
fclose(fi);
printf("%s:\n", argv[iarg]);
// elf header
ehdr = (Elf32_Ehdr *)buf;
shdr = (Elf32_Shdr *) (buf + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize);
shstr = (char *)(buf + shdr->sh_offset);
for (i = 0; i < ehdr->e_shnum; i++)
{
shdr = (Elf32_Shdr *) (buf + ehdr->e_shoff + i * ehdr->e_shentsize);
if (!shdr->sh_offset) continue;
if (shdr->sh_type == SHT_SYMTAB)
{
symtab = (char *)(buf + shdr->sh_offset);
symtabsize = shdr->sh_size;
}
if (shdr->sh_type == SHT_STRTAB)
{
if (!strcmp(shstr + shdr->sh_name, ".strtab"))
{
strtab = (char *)(buf + shdr->sh_offset);
strtabsize = shdr->sh_size;
}
}
}
if (symtab && symtabsize)
{
int nsym = symtabsize / sizeof(Elf32_Sym);
//printf("symtab: info size shndx name\n");
for (i = 1; i < nsym; i++)
{
sym = (Elf32_Sym *) (symtab + i * sizeof(Elf32_Sym));
if (sym->st_shndx && (sym->st_info == 0x11 || sym->st_info == 0x12)) {
//printf("symtab: %2Xh %4Xh %2Xh %s\n", sym->st_info, sym->st_size, sym->st_shndx, strtab + sym->st_name);
istrlen = strlen(strtab + sym->st_name)+1;
anames = realloc(anames, strpos+istrlen);
strcpy(anames + strpos, strtab + sym->st_name);
strpos += istrlen;
if (++funccnt >= funcmax) {
funcmax += 250;
afpos = realloc(afpos, funcmax * sizeof *afpos); // 250 func more
}
afpos[funccnt] = fpos;
}
}
}
memset(&arhdro.ar_name, ' ', sizeof(arhdr.ar_name));
strcpy(arhdro.ar_name, argv[iarg]);
arhdro.ar_name[strlen(argv[iarg])] = '/';
sprintf(stmp, "%-10d", fsize);
memcpy(&arhdro.ar_size, stmp, 10);
fwrite(&arhdro, sizeof(arhdro), 1, fo);
fwrite(buf, fsize, 1, fo);
free(buf);
iarg++;
fpos += (fsize + sizeof(arhdro));
}
hofs = 8 + sizeof(arhdr) + strpos + (funccnt+1) * sizeof(int);
if ((hofs & 1)) { // align
hofs++;
fpos = 1;
} else fpos = 0;
// write header
fwrite("!<arch>\n", 8, 1, fh);
sprintf(stmp, "%-10d", strpos + (funccnt+1) * sizeof(int));
memcpy(&arhdr.ar_size, stmp, 10);
fwrite(&arhdr, sizeof(arhdr), 1, fh);
afpos[0] = le2belong(funccnt);
for (i=1; i<=funccnt; i++) {
afpos[i] = le2belong(afpos[i] + hofs);
}
fwrite(afpos, (funccnt+1) * sizeof(int), 1, fh);
fwrite(anames, strpos, 1, fh);
if (fpos) fwrite("", 1, 1, fh);
// write objects
fseek(fo, 0, SEEK_END);
fsize = ftell(fo);
fseek(fo, 0, SEEK_SET);
buf = malloc(fsize + 1);
fread(buf, fsize, 1, fo);
fclose(fo);
fwrite(buf, fsize, 1, fh);
fclose(fh);
free(buf);
if (anames)
free(anames);
if (afpos)
free(afpos);
remove(tfile);
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/tools/tiny_libmaker.c | C | lgpl | 8,100 |
/* -------------------------------------------------------------- */
/*
* tiny_impdef creates an export definition file (.def) from a dll
* on MS-Windows. Usage: tiny_impdef library.dll [-o outputfile]"
*
* Copyright (c) 2005,2007 grischka
*
* 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.
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
/* Offset to PE file signature */
#define NTSIGNATURE(a) ((LPVOID)((BYTE *)a + \
((PIMAGE_DOS_HEADER)a)->e_lfanew))
/* MS-OS header identifies the NT PEFile signature dword;
the PEFILE header exists just after that dword. */
#define PEFHDROFFSET(a) ((LPVOID)((BYTE *)a + \
((PIMAGE_DOS_HEADER)a)->e_lfanew + \
SIZE_OF_NT_SIGNATURE))
/* PE optional header is immediately after PEFile header. */
#define OPTHDROFFSET(a) ((LPVOID)((BYTE *)a + \
((PIMAGE_DOS_HEADER)a)->e_lfanew + \
SIZE_OF_NT_SIGNATURE + \
sizeof (IMAGE_FILE_HEADER)))
/* Section headers are immediately after PE optional header. */
#define SECHDROFFSET(a) ((LPVOID)((BYTE *)a + \
((PIMAGE_DOS_HEADER)a)->e_lfanew + \
SIZE_OF_NT_SIGNATURE + \
sizeof (IMAGE_FILE_HEADER) + \
sizeof (IMAGE_OPTIONAL_HEADER)))
#define SIZE_OF_NT_SIGNATURE 4
/* -------------------------------------------------------------- */
int WINAPI NumOfSections (
LPVOID lpFile)
{
/* Number of sections is indicated in file header. */
return (int)
((PIMAGE_FILE_HEADER)
PEFHDROFFSET(lpFile))->NumberOfSections;
}
/* -------------------------------------------------------------- */
LPVOID WINAPI ImageDirectoryOffset (
LPVOID lpFile,
DWORD dwIMAGE_DIRECTORY)
{
PIMAGE_OPTIONAL_HEADER poh;
PIMAGE_SECTION_HEADER psh;
int nSections = NumOfSections (lpFile);
int i = 0;
LPVOID VAImageDir;
/* Retrieve offsets to optional and section headers. */
poh = (PIMAGE_OPTIONAL_HEADER)OPTHDROFFSET (lpFile);
psh = (PIMAGE_SECTION_HEADER)SECHDROFFSET (lpFile);
/* Must be 0 thru (NumberOfRvaAndSizes-1). */
if (dwIMAGE_DIRECTORY >= poh->NumberOfRvaAndSizes)
return NULL;
/* Locate image directory's relative virtual address. */
VAImageDir = (LPVOID)poh->DataDirectory[dwIMAGE_DIRECTORY].VirtualAddress;
/* Locate section containing image directory. */
while (i++<nSections)
{
if (psh->VirtualAddress <= (DWORD)VAImageDir
&& psh->VirtualAddress + psh->SizeOfRawData > (DWORD)VAImageDir)
break;
psh++;
}
if (i > nSections)
return NULL;
/* Return image import directory offset. */
return (LPVOID)(((int)lpFile +
(int)VAImageDir - psh->VirtualAddress) +
(int)psh->PointerToRawData);
}
/* -------------------------------------------------------------- */
BOOL WINAPI GetSectionHdrByName (
LPVOID lpFile,
IMAGE_SECTION_HEADER *sh,
char *szSection)
{
PIMAGE_SECTION_HEADER psh;
int nSections = NumOfSections (lpFile);
int i;
if ((psh = (PIMAGE_SECTION_HEADER)SECHDROFFSET (lpFile)) != NULL)
{
/* find the section by name */
for (i=0; i<nSections; i++)
{
if (!strcmp (psh->Name, szSection))
{
/* copy data to header */
memcpy ((LPVOID)sh, (LPVOID)psh, sizeof (IMAGE_SECTION_HEADER));
return TRUE;
}
else
psh++;
}
}
return FALSE;
}
/* -------------------------------------------------------------- */
BOOL WINAPI GetSectionHdrByAddress (
LPVOID lpFile,
IMAGE_SECTION_HEADER *sh,
DWORD addr)
{
PIMAGE_SECTION_HEADER psh;
int nSections = NumOfSections (lpFile);
int i;
if ((psh = (PIMAGE_SECTION_HEADER)SECHDROFFSET (lpFile)) != NULL)
{
/* find the section by name */
for (i=0; i<nSections; i++)
{
if (addr >= psh->VirtualAddress
&& addr < psh->VirtualAddress + psh->SizeOfRawData)
{
/* copy data to header */
memcpy ((LPVOID)sh, (LPVOID)psh, sizeof (IMAGE_SECTION_HEADER));
return TRUE;
}
else
psh++;
}
}
return FALSE;
}
/* -------------------------------------------------------------- */
int WINAPI GetExportFunctionNames (
LPVOID lpFile,
HANDLE hHeap,
char **pszFunctions)
{
IMAGE_SECTION_HEADER sh;
PIMAGE_EXPORT_DIRECTORY ped;
int *pNames, *pCnt;
char *pSrc, *pDest;
int i, nCnt;
DWORD VAImageDir;
PIMAGE_OPTIONAL_HEADER poh;
char *pOffset;
/* Get section header and pointer to data directory
for .edata section. */
if (NULL == (ped = (PIMAGE_EXPORT_DIRECTORY)
ImageDirectoryOffset (lpFile, IMAGE_DIRECTORY_ENTRY_EXPORT)))
return 0;
poh = (PIMAGE_OPTIONAL_HEADER)OPTHDROFFSET (lpFile);
VAImageDir = poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
if (FALSE == GetSectionHdrByAddress (lpFile, &sh, VAImageDir))
return 0;
pOffset = (char *)lpFile + (sh.PointerToRawData - sh.VirtualAddress);
pNames = (int *)(pOffset + (DWORD)ped->AddressOfNames);
/* Figure out how much memory to allocate for all strings. */
nCnt = 1;
for (i=0, pCnt = pNames; i<(int)ped->NumberOfNames; i++)
{
pSrc = (pOffset + *pCnt++);
if (pSrc)
nCnt += strlen(pSrc)+1;
}
/* Allocate memory off heap for function names. */
pDest = *pszFunctions = HeapAlloc (hHeap, HEAP_ZERO_MEMORY, nCnt);
/* Copy all strings to buffer. */
for (i=0, pCnt = pNames; i<(int)ped->NumberOfNames; i++)
{
pSrc = (pOffset + *pCnt++);
if (pSrc) {
strcpy(pDest, pSrc);
pDest += strlen(pSrc)+1;
}
}
*pDest = 0;
return ped->NumberOfNames;
}
/* -------------------------------------------------------------- */
/* extract the basename of a file */
static char *file_basename(const char *name)
{
const char *p = strchr(name, 0);
while (p > name
&& p[-1] != '/'
&& p[-1] != '\\'
)
--p;
return (char*)p;
}
/* -------------------------------------------------------------- */
int main(int argc, char **argv)
{
HANDLE hHeap;
HANDLE hFile;
HANDLE hMapObject;
VOID *pMem;
int nCnt, ret, n;
char *pNames;
char infile[MAX_PATH];
char buffer[MAX_PATH];
char outfile[MAX_PATH];
FILE *op;
char *p;
hHeap = NULL;
hFile = NULL;
hMapObject = NULL;
pMem = NULL;
infile[0] = 0;
outfile[0] = 0;
ret = 1;
for (n = 1; n < argc; ++n)
{
const char *a = argv[n];
if ('-' == a[0]) {
if (0 == strcmp(a, "-o")) {
if (++n == argc)
goto usage;
strcpy(outfile, argv[n]);
}
else
goto usage;
} else if (0 == infile[0])
strcpy(infile, a);
else
goto usage;
}
if (0 == infile[0])
{
usage:
fprintf(stderr,
"tiny_impdef creates an export definition file (.def) from a dll\n"
"Usage: tiny_impdef library.dll [-o outputfile]\n"
);
goto the_end;
}
if (SearchPath(NULL, infile, ".dll", sizeof buffer, buffer, NULL))
strcpy(infile, buffer);
if (0 == outfile[0])
{
char *p;
strcpy(outfile, file_basename(infile));
p = strrchr(outfile, '.');
if (NULL == p)
p = strchr(outfile, 0);
strcpy(p, ".def");
}
hFile = CreateFile(
infile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hFile == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "No such file: %s\n", infile);
goto the_end;
}
hMapObject = CreateFileMapping(
hFile,
NULL,
PAGE_READONLY,
0, 0,
NULL
);
if (NULL == hMapObject)
{
fprintf(stderr, "Could not create file mapping: %s\n", infile);
goto the_end;
}
pMem = MapViewOfFile(
hMapObject, // object to map view of
FILE_MAP_READ, // read access
0, // high offset: map from
0, // low offset: beginning
0); // default: map entire file
if (NULL == pMem)
{
fprintf(stderr, "Could not map view of file: %s\n", infile);
goto the_end;
}
if (0 != strncmp(NTSIGNATURE(pMem), "PE", 2))
{
fprintf(stderr, "Not a PE file: %s\n", infile);
goto the_end;
}
hHeap = GetProcessHeap();
nCnt = GetExportFunctionNames(pMem, hHeap, &pNames);
if (0 == nCnt) {
fprintf(stderr, "Could not get exported function names: %s\n", infile);
goto the_end;
}
printf("--> %s\n", infile);
op = fopen(outfile, "w");
if (NULL == op)
{
fprintf(stderr, "Could not create file: %s\n", outfile);
goto the_end;
}
printf("<-- %s\n", outfile);
fprintf(op, "LIBRARY %s\n\nEXPORTS\n", file_basename(infile));
for (n = 0, p = pNames; n < nCnt; ++n)
{
fprintf(op, "%s\n", p);
while (*p++);
}
ret = 0;
the_end:
if (pMem)
UnmapViewOfFile(pMem);
if (hMapObject)
CloseHandle(hMapObject);
if (hFile)
CloseHandle(hFile);
return ret;
}
/* -------------------------------------------------------------- */
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/tools/tiny_impdef.c | C | lgpl | 10,559 |
//+---------------------------------------------------------------------------
//
// dll.c - Windows DLL example - dynamically linked part
//
#include <windows.h>
#define DLL_EXPORT __declspec(dllexport)
DLL_EXPORT void HelloWorld (void)
{
MessageBox (0, "Hello World!", "From DLL", MB_ICONINFORMATION);
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/examples/dll.c | C | lgpl | 313 |
#include <stdio.h>
int fib(n)
{
if (n <= 2)
return 1;
else
return fib(n-1) + fib(n-2);
}
int main(int argc, char **argv)
{
int n;
if (argc < 2) {
printf("usage: fib n\n"
"Compute nth Fibonacci number\n");
return 1;
}
n = atoi(argv[1]);
printf("fib(%d) = %d\n", n, fib(n));
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/examples/fib.c | C | lgpl | 313 |
//+---------------------------------------------------------------------------
//
// HELLO_DLL.C - Windows DLL example - main application part
//
#include <windows.h>
void HelloWorld (void);
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
HelloWorld();
return 0;
}
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/examples/hello_dll.c | C | lgpl | 337 |
//+---------------------------------------------------------------------------
//
// HELLO_WIN.C - Windows GUI 'Hello World!' Example
//
//+---------------------------------------------------------------------------
#include <windows.h>
#define APPNAME "HELLO_WIN"
char szAppName[] = APPNAME; // The name of this application
char szTitle[] = APPNAME; // The title bar text
char *pWindowText;
HINSTANCE g_hInst; // current instance
void CenterWindow(HWND hWnd);
//+---------------------------------------------------------------------------
//
// Function: WndProc
//
// Synopsis: very unusual type of function - gets called by system to
// process windows messages.
//
// Arguments: same as always.
//----------------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
// ----------------------- first and last
case WM_CREATE:
CenterWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
// ----------------------- get out of it...
case WM_RBUTTONUP:
DestroyWindow(hwnd);
break;
case WM_KEYDOWN:
if (VK_ESCAPE == wParam)
DestroyWindow(hwnd);
break;
// ----------------------- display our minimal info
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc;
RECT rc;
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rc);
SetTextColor(hdc, RGB(240,240,96));
SetBkMode(hdc, TRANSPARENT);
DrawText(hdc, pWindowText, -1, &rc, DT_CENTER|DT_SINGLELINE|DT_VCENTER);
EndPaint(hwnd, &ps);
break;
}
// ----------------------- let windows do all other stuff
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
//+---------------------------------------------------------------------------
//
// Function: WinMain
//
// Synopsis: standard entrypoint for GUI Win32 apps
//
//----------------------------------------------------------------------------
int APIENTRY WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
WNDCLASS wc;
HWND hwnd;
// Fill in window class structure with parameters that describe
// the main window.
ZeroMemory(&wc, sizeof wc);
wc.hInstance = hInstance;
wc.lpszClassName = szAppName;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.style = CS_DBLCLKS|CS_VREDRAW|CS_HREDRAW;
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (FALSE == RegisterClass(&wc)) return 0;
// create the browser
hwnd = CreateWindow(
szAppName,
szTitle,
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
360,//CW_USEDEFAULT,
240,//CW_USEDEFAULT,
0,
0,
g_hInst,
0);
if (NULL == hwnd) return 0;
pWindowText = lpCmdLine[0] ? lpCmdLine : "Hello Windows!";
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
//+---------------------------------------------------------------------------
//+---------------------------------------------------------------------------
void CenterWindow(HWND hwnd_self)
{
RECT rw_self, rc_parent, rw_parent; HWND hwnd_parent;
hwnd_parent = GetParent(hwnd_self);
if (NULL==hwnd_parent) hwnd_parent = GetDesktopWindow();
GetWindowRect(hwnd_parent, &rw_parent);
GetClientRect(hwnd_parent, &rc_parent);
GetWindowRect(hwnd_self, &rw_self);
SetWindowPos(hwnd_self, NULL,
rw_parent.left + (rc_parent.right + rw_self.left - rw_self.right) / 2,
rw_parent.top + (rc_parent.bottom + rw_self.top - rw_self.bottom) / 2,
0, 0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE
);
}
//+---------------------------------------------------------------------------
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/examples/hello_win.c | C | lgpl | 3,897 |
/*
* _mingw.h
*
* This file is for TCC-PE and not part of the Mingw32 package.
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef __MINGW_H
#define __MINGW_H
#include <stddef.h>
#define __int64 long long
#define __int32 long
#define __int16 short
#define __int8 char
#define __cdecl __attribute__((__cdecl__))
#define __stdcall __attribute__((__stdcall__))
#define __declspec(x) __attribute__((x))
#define __MINGW32_VERSION 2.0
#define __MINGW32_MAJOR_VERSION 2
#define __MINGW32_MINOR_VERSION 0
#define __MSVCRT__ 1
#define __MINGW_IMPORT extern
#define _CRTIMP
#define __CRT_INLINE extern __inline__
#define WIN32 1
#ifndef _WINT_T
#define _WINT_T
typedef unsigned int wint_t;
#endif
/* for winapi */
#define _ANONYMOUS_UNION
#define _ANONYMOUS_STRUCT
#define DECLSPEC_NORETURN
#define WIN32_LEAN_AND_MEAN
#define DECLARE_STDCALL_P(type) __stdcall type
#endif /* __MINGW_H */
| zzl-compiler | trunk -m 'initial import'/tcc-0.9.25/win32/include/_mingw.h | C | lgpl | 1,275 |