repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
tebeka/arrow
csharp/src/Apache.Arrow/Types/Int8Type.cs
1248
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Apache.Arrow.Types { public sealed class Int8Type : NumberType { public static readonly Int8Type Default = new Int8Type(); public override ArrowTypeId TypeId => ArrowTypeId.Int8; public override string Name => "int8"; public override int BitWidth => 8; public override bool IsSigned => true; public override void Accept(IArrowTypeVisitor visitor) => Accept(this, visitor); } }
apache-2.0
Microsoft/TypeScript
tests/baselines/reference/crashIntypeCheckInvocationExpression.js
858
//// [crashIntypeCheckInvocationExpression.ts] var nake; function doCompile<P0, P1, P2>(fileset: P0, moduleType: P1) { return undefined; } export var compileServer = task<number, number, any>(<P0, P1, P2>() => { var folder = path.join(), fileset = nake.fileSetSync<number, number, any>(folder) return doCompile<number, number, any>(fileset, moduleType); }); //// [crashIntypeCheckInvocationExpression.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.compileServer = void 0; var nake; function doCompile(fileset, moduleType) { return undefined; } exports.compileServer = task(function () { var folder = path.join(), fileset = nake.fileSetSync(folder); return doCompile(fileset, moduleType); }); });
apache-2.0
cjwagner/test-infra
prow/git/git_test.go
15553
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This test imports "k8s.io/test-infra/prow/git/localgit", which also reference // "k8s.io/test-infra/prow/git", has to be a separate package to avoid // circular dependency(however this file implicitly referencing "k8s.io/test-infra/prow/git") package git_test import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "testing" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/git/localgit" "k8s.io/test-infra/prow/github" ) var defaultBranch = localgit.DefaultBranch("") func TestClone(t *testing.T) { testClone(localgit.New, t) } func TestCloneV2(t *testing.T) { testClone(localgit.NewV2, t) } func testClone(clients localgit.Clients, t *testing.T) { lg, c, err := clients() if err != nil { t.Fatalf("Making local git repo: %v", err) } defer func() { if err := lg.Clean(); err != nil { t.Errorf("Error cleaning LocalGit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Error cleaning Client: %v", err) } }() if err := lg.MakeFakeRepo("foo", "bar"); err != nil { t.Fatalf("Making fake repo: %v", err) } if err := lg.MakeFakeRepo("foo", "baz"); err != nil { t.Fatalf("Making fake repo: %v", err) } // Fresh clone, will be a cache miss. r1, err := c.ClientFor("foo", "bar") if err != nil { t.Fatalf("Cloning the first time: %v", err) } defer func() { if err := r1.Clean(); err != nil { t.Errorf("Cleaning repo: %v", err) } }() // Clone from the same org. r2, err := c.ClientFor("foo", "baz") if err != nil { t.Fatalf("Cloning another repo in the same org: %v", err) } defer func() { if err := r2.Clean(); err != nil { t.Errorf("Cleaning repo: %v", err) } }() // Make sure it fetches when we clone again. if err := lg.AddCommit("foo", "bar", map[string][]byte{"second": {}}); err != nil { t.Fatalf("Adding second commit: %v", err) } r3, err := c.ClientFor("foo", "bar") if err != nil { t.Fatalf("Cloning a second time: %v", err) } defer func() { if err := r3.Clean(); err != nil { t.Errorf("Cleaning repo: %v", err) } }() log := exec.Command("git", "log", "--oneline") log.Dir = r3.Directory() if b, err := log.CombinedOutput(); err != nil { t.Fatalf("git log: %v, %s", err, string(b)) } else { t.Logf("git log output: %s", string(b)) if len(bytes.Split(bytes.TrimSpace(b), []byte("\n"))) != 2 { t.Error("Wrong number of commits in git log output. Expected 2") } } } func TestCheckoutPR(t *testing.T) { testCheckoutPR(localgit.New, t) } func TestCheckoutPRV2(t *testing.T) { testCheckoutPR(localgit.NewV2, t) } func testCheckoutPR(clients localgit.Clients, t *testing.T) { lg, c, err := clients() if err != nil { t.Fatalf("Making local git repo: %v", err) } defer func() { if err := lg.Clean(); err != nil { t.Errorf("Error cleaning LocalGit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Error cleaning Client: %v", err) } }() if err := lg.MakeFakeRepo("foo", "bar"); err != nil { t.Fatalf("Making fake repo: %v", err) } r, err := c.ClientFor("foo", "bar") if err != nil { t.Fatalf("Cloning: %v", err) } defer func() { if err := r.Clean(); err != nil { t.Errorf("Cleaning repo: %v", err) } }() if err := lg.CheckoutNewBranch("foo", "bar", "pull/123/head"); err != nil { t.Fatalf("Checkout new branch: %v", err) } if err := lg.AddCommit("foo", "bar", map[string][]byte{"wow": {}}); err != nil { t.Fatalf("Add commit: %v", err) } if err := r.CheckoutPullRequest(123); err != nil { t.Fatalf("Checking out PR: %v", err) } if _, err := os.Stat(filepath.Join(r.Directory(), "wow")); err != nil { t.Errorf("Didn't find file in PR after checking out: %v", err) } } func TestMergeCommitsExistBetween(t *testing.T) { testMergeCommitsExistBetween(localgit.New, t) } func TestMergeCommitsExistBetweenV2(t *testing.T) { testMergeCommitsExistBetween(localgit.NewV2, t) } func testMergeCommitsExistBetween(clients localgit.Clients, t *testing.T) { lg, c, err := clients() if err != nil { t.Fatalf("Making local git repo: %v", err) } defer func() { if err := lg.Clean(); err != nil { t.Errorf("Cleaning up localgit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Cleaning up client: %v", err) } }() if err := lg.MakeFakeRepo("foo", "bar"); err != nil { t.Fatalf("Making fake repo: %v", err) } r, err := c.ClientFor("foo", "bar") if err != nil { t.Fatalf("Cloning: %v", err) } defer func() { if err := r.Clean(); err != nil { t.Errorf("Cleaning repo: %v", err) } }() var ( checkoutPR = func(prNum int) { if err := lg.CheckoutNewBranch("foo", "bar", fmt.Sprintf("pull/%d/head", prNum)); err != nil { t.Fatalf("Creating & checking out pull branch pull/%d/head: %v", prNum, err) } } checkoutBranch = func(branch string) { if err := lg.Checkout("foo", "bar", branch); err != nil { t.Fatalf("Checking out branch %s: %v", branch, err) } } addCommit = func(file string) { if err := lg.AddCommit("foo", "bar", map[string][]byte{file: {}}); err != nil { t.Fatalf("Adding commit: %v", err) } } mergeMaster = func() { if _, err := lg.Merge("foo", "bar", defaultBranch); err != nil { t.Fatalf("Rebasing commit: %v", err) } } rebaseMaster = func() { if _, err := lg.Rebase("foo", "bar", defaultBranch); err != nil { t.Fatalf("Rebasing commit: %v", err) } } ) type testCase struct { name string prNum int checkout func() mergeOrRebase func() checkoutPR func() error want bool } testcases := []testCase{ { name: "PR has merge commits", prNum: 1, checkout: func() { checkoutBranch("pull/1/head") }, mergeOrRebase: mergeMaster, checkoutPR: func() error { return r.CheckoutPullRequest(1) }, want: true, }, { name: "PR doesn't have merge commits", prNum: 2, checkout: func() { checkoutBranch("pull/2/head") }, mergeOrRebase: rebaseMaster, checkoutPR: func() error { return r.CheckoutPullRequest(2) }, want: false, }, } addCommit("wow") // preparation work: branch off all prs upon commit 'wow' for _, tt := range testcases { checkoutPR(tt.prNum) } // switch back to master and create a new commit 'ouch' checkoutBranch(defaultBranch) addCommit("ouch") masterSHA, err := lg.RevParse("foo", "bar", "HEAD") if err != nil { t.Fatalf("Fetching SHA: %v", err) } for _, tt := range testcases { tt.checkout() tt.mergeOrRebase() prSHA, err := lg.RevParse("foo", "bar", "HEAD") if err != nil { t.Fatalf("Fetching SHA: %v", err) } if err := tt.checkoutPR(); err != nil { t.Fatalf("Checking out PR: %v", err) } // verify the content is up to dated ouchPath := filepath.Join(r.Directory(), "ouch") if _, err := os.Stat(ouchPath); err != nil { t.Fatalf("Didn't find file 'ouch' in PR %d after merging: %v", tt.prNum, err) } got, err := r.MergeCommitsExistBetween(masterSHA, prSHA) key := fmt.Sprintf("foo/bar/%d", tt.prNum) if err != nil { t.Errorf("Case: %v. Expect err is nil, but got %v", key, err) } if tt.want != got { t.Errorf("Case: %v. Expect MergeCommitsExistBetween()=%v, but got %v", key, tt.want, got) } } } func TestMergeAndCheckout(t *testing.T) { testMergeAndCheckout(localgit.New, t) } func TestMergeAndCheckoutV2(t *testing.T) { testMergeAndCheckout(localgit.NewV2, t) } func testMergeAndCheckout(clients localgit.Clients, t *testing.T) { testCases := []struct { name string setBaseSHA bool prBranches []string mergeStrategy github.PullRequestMergeType err string }{ { name: "Unset baseSHA, error", err: "baseSHA must be set", }, { name: "No mergeStrategy, error", setBaseSHA: true, prBranches: []string{"my-pr-branch"}, err: "merge strategy \"\" is not supported", }, { name: "Merge strategy rebase, error", setBaseSHA: true, prBranches: []string{"my-pr-branch"}, mergeStrategy: github.MergeRebase, err: "merge strategy \"rebase\" is not supported", }, { name: "No pullRequestHead, no error", setBaseSHA: true, }, { name: "Merge succeeds with one head and merge strategy", setBaseSHA: true, prBranches: []string{"my-pr-branch"}, mergeStrategy: github.MergeMerge, }, { name: "Merge succeeds with multiple heads and merge strategy", setBaseSHA: true, prBranches: []string{"my-pr-branch", "my-other-pr-branch"}, mergeStrategy: github.MergeMerge, }, { name: "Merge succeeds with one head and squash strategy", setBaseSHA: true, prBranches: []string{"my-pr-branch"}, mergeStrategy: github.MergeSquash, }, { name: "Merge succeeds with multiple heads and squash stragey", setBaseSHA: true, prBranches: []string{"my-pr-branch", "my-other-pr-branch"}, mergeStrategy: github.MergeSquash, }, } const ( org = "my-org" repo = "my-repo" ) for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { tc := tc t.Parallel() lg, c, err := clients() if err != nil { t.Fatalf("Making local git repo: %v", err) } logrus.SetLevel(logrus.DebugLevel) defer func() { if err := lg.Clean(); err != nil { t.Errorf("Error cleaning LocalGit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Error cleaning Client: %v", err) } }() if err := lg.MakeFakeRepo(org, repo); err != nil { t.Fatalf("Making fake repo: %v", err) } var commitsToMerge []string for _, prBranch := range tc.prBranches { if err := lg.CheckoutNewBranch(org, repo, prBranch); err != nil { t.Fatalf("failed to checkout new branch %q: %v", prBranch, err) } if err := lg.AddCommit(org, repo, map[string][]byte{prBranch: []byte("val")}); err != nil { t.Fatalf("failed to add commit: %v", err) } headRef, err := lg.RevParse(org, repo, "HEAD") if err != nil { t.Fatalf("failed to run git rev-parse: %v", err) } commitsToMerge = append(commitsToMerge, headRef) } if len(tc.prBranches) > 0 { if err := lg.Checkout(org, repo, defaultBranch); err != nil { t.Fatalf("failed to run git checkout master: %v", err) } } var baseSHA string if tc.setBaseSHA { baseSHA, err = lg.RevParse(org, repo, defaultBranch) if err != nil { t.Fatalf("failed to run git rev-parse master: %v", err) } } clonedRepo, err := c.ClientFor(org, repo) if err != nil { t.Fatalf("Cloning failed: %v", err) } if err := clonedRepo.Config("user.name", "prow"); err != nil { t.Fatalf("failed to set name for test repo: %v", err) } if err := clonedRepo.Config("user.email", "prow@localhost"); err != nil { t.Fatalf("failed to set email for test repo: %v", err) } if err := clonedRepo.Config("commit.gpgsign", "false"); err != nil { t.Fatalf("failed to disable gpg signing for test repo: %v", err) } err = clonedRepo.MergeAndCheckout(baseSHA, string(tc.mergeStrategy), commitsToMerge...) if err == nil && tc.err == "" { return } if err == nil || err.Error() != tc.err { t.Errorf("Expected err %q but got \"%v\"", tc.err, err) } }) } } func TestMerging(t *testing.T) { testMerging(localgit.New, t) } func TestMergingV2(t *testing.T) { testMerging(localgit.NewV2, t) } func testMerging(clients localgit.Clients, t *testing.T) { testCases := []struct { name string strategy string // branch -> filename -> content branches map[string]map[string][]byte mergeOrder []string }{ { name: "Multiple branches, squash strategy", strategy: "squash", branches: map[string]map[string][]byte{ "pr-1": {"file-1": []byte("some-content")}, "pr-2": {"file-2": []byte("some-content")}, }, mergeOrder: []string{"pr-1", "pr-2"}, }, { name: "Multiple branches, mergeMerge strategy", strategy: "merge", branches: map[string]map[string][]byte{ "pr-1": {"file-1": []byte("some-content")}, "pr-2": {"file-2": []byte("some-content")}, }, mergeOrder: []string{"pr-1", "pr-2"}, }, } const org, repo = "org", "repo" for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { tc := tc t.Parallel() lg, c, err := clients() if err != nil { t.Fatalf("Making local git repo: %v", err) } logrus.SetLevel(logrus.DebugLevel) defer func() { if err := lg.Clean(); err != nil { t.Errorf("Error cleaning LocalGit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Error cleaning Client: %v", err) } }() if err := lg.MakeFakeRepo(org, repo); err != nil { t.Fatalf("Making fake repo: %v", err) } baseSHA, err := lg.RevParse(org, repo, "HEAD") if err != nil { t.Fatalf("rev-parse HEAD: %v", err) } for branchName, branchContent := range tc.branches { if err := lg.Checkout(org, repo, baseSHA); err != nil { t.Fatalf("checkout baseSHA: %v", err) } if err := lg.CheckoutNewBranch(org, repo, branchName); err != nil { t.Fatalf("checkout new branch: %v", err) } if err := lg.AddCommit(org, repo, branchContent); err != nil { t.Fatalf("addCommit: %v", err) } } if err := lg.Checkout(org, repo, baseSHA); err != nil { t.Fatalf("checkout baseSHA: %v", err) } r, err := c.ClientFor(org, repo) if err != nil { t.Fatalf("clone: %v", err) } if err := r.Config("user.name", "prow"); err != nil { t.Fatalf("config user.name: %v", err) } if err := r.Config("user.email", "prow@localhost"); err != nil { t.Fatalf("config user.email: %v", err) } if err := r.Checkout(baseSHA); err != nil { t.Fatalf("checkout baseSHA: %v", err) } for _, branch := range tc.mergeOrder { if _, err := r.MergeWithStrategy("origin/"+branch, tc.strategy); err != nil { t.Fatalf("mergeWithStrategy %s: %v", branch, err) } } }) } } func TestShowRef(t *testing.T) { testShowRef(localgit.New, t) } func TestShowRefV2(t *testing.T) { testShowRef(localgit.NewV2, t) } func testShowRef(clients localgit.Clients, t *testing.T) { const org, repo = "org", "repo" lg, c, err := clients() if err != nil { t.Fatalf("failed to get clients: %v", err) } defer func() { if err := lg.Clean(); err != nil { t.Errorf("Error cleaning LocalGit: %v", err) } if err := c.Clean(); err != nil { t.Errorf("Error cleaning Client: %v", err) } }() if err := lg.MakeFakeRepo(org, repo); err != nil { t.Fatalf("Making fake repo: %v", err) } reference, err := lg.RevParse(org, repo, "HEAD") if err != nil { t.Fatalf("lg.RevParse: %v", err) } client, err := c.ClientFor(org, repo) if err != nil { t.Fatalf("clientFor: %v", err) } res, err := client.ShowRef("HEAD") if err != nil { t.Fatalf("ShowRef: %v", err) } if res != reference { t.Errorf("expeted result to be %s, was %s", reference, res) } }
apache-2.0
tas50/supermarket
src/supermarket/spec/api/cookbook_contingent_spec.rb
1174
require 'spec_helper' describe 'GET /api/v1/cookbooks/:cookbook/contingent' do context 'when the cookbook exists' do let(:apt) { create(:cookbook, name: 'apt') } let(:nginx) { create(:cookbook, name: 'nginx') } let(:apache) { create(:cookbook, name: 'apache') } before do create(:cookbook_dependency, cookbook: apt, cookbook_version: nginx.latest_cookbook_version) create(:cookbook_dependency, cookbook: apt, cookbook_version: apache.latest_cookbook_version) get '/api/v1/cookbooks/apt/contingent' end it 'returns a 200' do expect(response.status.to_i).to eql(200) end it 'returns the cookbooks' do contingents = json_body['contingents'] expect(contingents.size).to eql(2) expect(contingents.first['name']).to eql('apache') expect(contingents.last['name']).to eql('nginx') end end context 'when the cookbook does not exist' do it 'returns a 404' do get '/api/v1/cookbooks/mamimi' expect(response.status.to_i).to eql(404) end it 'returns a 404 message' do get '/api/v1/cookbooks/mamimi' expect(json_body).to eql(error_404) end end end
apache-2.0
mdecourci/assertj-core
src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_usingElementComparatorIgnoringFields_Test.java
1959
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.api.objectarray; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.ObjectArrayAssert; import org.assertj.core.api.ObjectArrayAssertBaseTest; import org.assertj.core.internal.ComparatorBasedComparisonStrategy; import org.assertj.core.internal.IgnoringFieldsComparator; import org.assertj.core.internal.ObjectArrays; import org.junit.Before; public class ObjectArrayAssert_usingElementComparatorIgnoringFields_Test extends ObjectArrayAssertBaseTest { private ObjectArrays arraysBefore; @Before public void before() { arraysBefore = getArrays(assertions); } @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.usingElementComparatorIgnoringFields("field"); } @Override protected void verify_internal_effects() { ObjectArrays iterables = getArrays(assertions); assertThat(iterables).isNotSameAs(arraysBefore); assertThat(iterables.getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class); ComparatorBasedComparisonStrategy strategy = (ComparatorBasedComparisonStrategy) iterables.getComparisonStrategy(); assertThat(strategy.getComparator()).isInstanceOf(IgnoringFieldsComparator.class); assertThat(((IgnoringFieldsComparator) strategy.getComparator()).getFields()).containsOnly("field"); } }
apache-2.0
efortuna/AndroidSDKClone
sdk/samples/android-20/legacy/XmlAdapters/src/com/example/android/xmladapters/UrlIntentListener.java
1446
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.xmladapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; /** * A listener which expects a URL as a tag of the view it is associated with. It then opens the URL * in the browser application. */ public class UrlIntentListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final String url = view.getTag().toString(); final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final Context context = parent.getContext(); context.startActivity(intent); } }
apache-2.0
google/aistreams
third_party/gst-plugins-base/tests/check/elements/opus.c
16126
/* GStreamer * * unit test for opus * * Copyright (C) <2011> Vincent Penquerc'h <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/check/gstcheck.h> #include <gst/check/gstharness.h> #if G_BYTE_ORDER == G_BIG_ENDIAN #define AFORMAT "S16BE" #else #define AFORMAT "S16LE" #endif #define AUDIO_CAPS_STRING "audio/x-raw, " \ "format = (string) " AFORMAT ", "\ "layout = (string) interleaved, " \ "rate = (int) 48000, " \ "channels = (int) 1 " /* A lot of these taken from the vorbisdec test */ /* For ease of programming we use globals to keep refs for our floating * src and sink pads we create; otherwise we always have to do get_pad, * get_peer, and then remove references in every test function */ static GstPad *mydecsrcpad, *mydecsinkpad; static GstPad *myencsrcpad, *myencsinkpad; static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); static GstElement * setup_opusdec (void) { GstElement *opusdec; GST_DEBUG ("setup_opusdec"); opusdec = gst_check_setup_element ("opusdec"); mydecsrcpad = gst_check_setup_src_pad (opusdec, &srctemplate); mydecsinkpad = gst_check_setup_sink_pad (opusdec, &sinktemplate); gst_pad_set_active (mydecsrcpad, TRUE); gst_pad_set_active (mydecsinkpad, TRUE); return opusdec; } static void cleanup_opusdec (GstElement * opusdec) { GST_DEBUG ("cleanup_opusdec"); gst_element_set_state (opusdec, GST_STATE_NULL); gst_pad_set_active (mydecsrcpad, FALSE); gst_pad_set_active (mydecsinkpad, FALSE); gst_check_teardown_src_pad (opusdec); gst_check_teardown_sink_pad (opusdec); gst_check_teardown_element (opusdec); } static GstElement * setup_opusenc (void) { GstElement *opusenc; GST_DEBUG ("setup_opusenc"); opusenc = gst_check_setup_element ("opusenc"); myencsrcpad = gst_check_setup_src_pad (opusenc, &srctemplate); myencsinkpad = gst_check_setup_sink_pad (opusenc, &sinktemplate); gst_pad_set_active (myencsrcpad, TRUE); gst_pad_set_active (myencsinkpad, TRUE); return opusenc; } static void cleanup_opusenc (GstElement * opusenc) { GST_DEBUG ("cleanup_opusenc"); gst_element_set_state (opusenc, GST_STATE_NULL); gst_pad_set_active (myencsrcpad, FALSE); gst_pad_set_active (myencsinkpad, FALSE); gst_check_teardown_src_pad (opusenc); gst_check_teardown_sink_pad (opusenc); gst_check_teardown_element (opusenc); } static void check_buffers (guint expected) { GstBuffer *outbuffer; guint i, num_buffers; /* check buffers are the type we expect */ num_buffers = g_list_length (buffers); fail_unless (num_buffers >= expected); for (i = 0; i < num_buffers; ++i) { outbuffer = GST_BUFFER (buffers->data); fail_if (outbuffer == NULL); fail_if (gst_buffer_get_size (outbuffer) == 0); buffers = g_list_remove (buffers, outbuffer); ASSERT_BUFFER_REFCOUNT (outbuffer, "outbuffer", 1); gst_buffer_unref (outbuffer); outbuffer = NULL; } } GST_START_TEST (test_opus_encode_nothing) { GstElement *opusenc; opusenc = setup_opusenc (); fail_unless (gst_element_set_state (opusenc, GST_STATE_PLAYING) == GST_STATE_CHANGE_SUCCESS, "could not set to playing"); fail_unless (gst_pad_push_event (myencsrcpad, gst_event_new_eos ()) == TRUE); fail_unless (gst_element_set_state (opusenc, GST_STATE_READY) == GST_STATE_CHANGE_SUCCESS, "could not set to ready"); /* cleanup */ cleanup_opusenc (opusenc); } GST_END_TEST; GST_START_TEST (test_opus_decode_nothing) { GstElement *opusdec; opusdec = setup_opusdec (); fail_unless (gst_element_set_state (opusdec, GST_STATE_PLAYING) == GST_STATE_CHANGE_SUCCESS, "could not set to playing"); fail_unless (gst_pad_push_event (mydecsrcpad, gst_event_new_eos ()) == TRUE); fail_unless (gst_element_set_state (opusdec, GST_STATE_READY) == GST_STATE_CHANGE_SUCCESS, "could not set to ready"); /* cleanup */ cleanup_opusdec (opusdec); } GST_END_TEST; GST_START_TEST (test_opus_encode_samples) { const unsigned int nsamples = 4096; GstElement *opusenc; GstBuffer *inbuffer; GstCaps *caps; opusenc = setup_opusenc (); fail_unless (gst_element_set_state (opusenc, GST_STATE_PLAYING) == GST_STATE_CHANGE_SUCCESS, "could not set to playing"); inbuffer = gst_buffer_new_and_alloc (nsamples * 2); gst_buffer_memset (inbuffer, 0, 0, nsamples * 2); GST_BUFFER_TIMESTAMP (inbuffer) = GST_BUFFER_OFFSET (inbuffer) = 0; GST_BUFFER_DURATION (inbuffer) = GST_CLOCK_TIME_NONE; ASSERT_BUFFER_REFCOUNT (inbuffer, "inbuffer", 1); caps = gst_caps_from_string (AUDIO_CAPS_STRING); fail_unless (caps != NULL); gst_check_setup_events (myencsrcpad, opusenc, caps, GST_FORMAT_TIME); gst_caps_unref (caps); gst_buffer_ref (inbuffer); /* pushing gives away my reference ... */ fail_unless (gst_pad_push (myencsrcpad, inbuffer) == GST_FLOW_OK); /* ... and nothing ends up on the global buffer list */ fail_unless (gst_pad_push_event (myencsrcpad, gst_event_new_eos ()) == TRUE); ASSERT_BUFFER_REFCOUNT (inbuffer, "inbuffer", 1); gst_buffer_unref (inbuffer); fail_unless (gst_element_set_state (opusenc, GST_STATE_READY) == GST_STATE_CHANGE_SUCCESS, "could not set to ready"); /* default frame size is 20 ms, at 48000 Hz that's 960 samples */ check_buffers ((nsamples + 959) / 960); /* cleanup */ cleanup_opusenc (opusenc); g_list_free (buffers); } GST_END_TEST; GST_START_TEST (test_opus_encode_properties) { const unsigned int nsamples = 4096; enum { steps = 20 }; GstElement *opusenc; GstBuffer *inbuffer; GstCaps *caps; unsigned int step; static const struct { const char *param; int value; } param_changes[steps] = { { "frame-size", 40}, { "inband-fec", 1}, { "complexity", 5}, { "bandwidth", 1104}, { "frame-size", 2}, { "max-payload-size", 80}, { "frame-size", 60}, { "max-payload-size", 900}, { "complexity", 1}, { "bitrate", 30000}, { "frame-size", 10}, { "bitrate", 300000}, { "inband-fec", 0}, { "frame-size", 5}, { "bandwidth", 1101}, { "frame-size", 10}, { "bitrate", 500000}, { "frame-size", 5}, { "bitrate", 80000}, { "complexity", 8},}; opusenc = setup_opusenc (); fail_unless (gst_element_set_state (opusenc, GST_STATE_PLAYING) == GST_STATE_CHANGE_SUCCESS, "could not set to playing"); caps = gst_caps_from_string (AUDIO_CAPS_STRING); fail_unless (caps != NULL); gst_check_setup_events (myencsrcpad, opusenc, caps, GST_FORMAT_TIME); for (step = 0; step < steps; ++step) { GstSegment segment; gst_segment_init (&segment, GST_FORMAT_TIME); gst_pad_push_event (myencsrcpad, gst_event_new_segment (&segment)); inbuffer = gst_buffer_new_and_alloc (nsamples * 2); gst_buffer_memset (inbuffer, 0, 0, nsamples * 2); GST_BUFFER_TIMESTAMP (inbuffer) = GST_BUFFER_OFFSET (inbuffer) = 0; GST_BUFFER_DURATION (inbuffer) = GST_CLOCK_TIME_NONE; ASSERT_BUFFER_REFCOUNT (inbuffer, "inbuffer", 1); gst_buffer_ref (inbuffer); /* pushing gives away my reference ... */ fail_unless (gst_pad_push (myencsrcpad, inbuffer) == GST_FLOW_OK); /* ... and nothing ends up on the global buffer list */ fail_unless (gst_pad_push_event (myencsrcpad, gst_event_new_eos ()) == TRUE); ASSERT_BUFFER_REFCOUNT (inbuffer, "inbuffer", 1); gst_buffer_unref (inbuffer); /* change random parameters */ g_object_set (opusenc, param_changes[step].param, param_changes[step].value, NULL); check_buffers (1); fail_unless (gst_pad_push_event (myencsrcpad, gst_event_new_flush_start ()) == TRUE); fail_unless (gst_pad_push_event (myencsrcpad, gst_event_new_flush_stop (TRUE)) == TRUE); } gst_caps_unref (caps); fail_unless (gst_element_set_state (opusenc, GST_STATE_READY) == GST_STATE_CHANGE_SUCCESS, "could not set to ready"); /* cleanup */ cleanup_opusenc (opusenc); g_list_free (buffers); } GST_END_TEST; /* removes fields that do not interest our tests to * allow using gst_caps_is_equal for comparison */ static GstCaps * remove_extra_caps_fields (GstCaps * caps) { gint i; for (i = 0; i < gst_caps_get_size (caps); i++) { GstStructure *s = gst_caps_get_structure (caps, i); gst_structure_remove_field (s, "channel-mapping-family"); gst_structure_remove_field (s, "coupled-count"); gst_structure_remove_field (s, "stream-count"); } return gst_caps_simplify (caps); } static void run_getcaps_check (GstCaps * filter, GstCaps * downstream_caps, GstCaps * expected_result) { GstElement *opusdec; GstElement *capsfilter; GstPad *sinkpad; GstCaps *result; gchar *caps_str; opusdec = gst_element_factory_make ("opusdec", NULL); capsfilter = gst_element_factory_make ("capsfilter", NULL); sinkpad = gst_element_get_static_pad (opusdec, "sink"); fail_unless (gst_element_link (opusdec, capsfilter)); if (downstream_caps) g_object_set (capsfilter, "caps", downstream_caps, NULL); result = gst_pad_query_caps (sinkpad, filter); result = remove_extra_caps_fields (result); caps_str = gst_caps_to_string (result); fail_unless (gst_caps_is_equal (expected_result, result), "Unexpected output caps: %s", caps_str); if (filter) gst_caps_unref (filter); gst_caps_unref (result); gst_caps_unref (expected_result); if (downstream_caps) gst_caps_unref (downstream_caps); gst_object_unref (sinkpad); gst_object_unref (opusdec); gst_object_unref (capsfilter); g_free (caps_str); } static void run_getcaps_check_from_strings (const gchar * filter, const gchar * downstream_caps, const gchar * expected_result) { run_getcaps_check (filter ? gst_caps_from_string (filter) : NULL, downstream_caps ? gst_caps_from_string (downstream_caps) : NULL, gst_caps_from_string (expected_result)); } GST_START_TEST (test_opusdec_getcaps) { /* default result */ run_getcaps_check_from_strings (NULL, NULL, "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,8]"); /* A single supported rate downstream - should accept any upstream anyway */ run_getcaps_check_from_strings (NULL, "audio/x-raw, rate=(int)8000", "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,8]"); /* Two supported rates (fields as a array, not as a single int) */ run_getcaps_check_from_strings (NULL, "audio/x-raw, rate=(int){24000, 8000}", "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,8]"); /* One supported and one unsupported rate */ run_getcaps_check_from_strings (NULL, "audio/x-raw, rate=(int){24000, 1000}", "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,8]"); /* Unsupported rate */ run_getcaps_check_from_strings (NULL, "audio/x-raw, rate=(int)1000", "EMPTY"); /* same tests for channels */ run_getcaps_check_from_strings (NULL, "audio/x-raw, channels=(int)2", "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,2]"); run_getcaps_check_from_strings (NULL, "audio/x-raw, channels=(int)[1, 2]", "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)[1,2]"); run_getcaps_check_from_strings (NULL, "audio/x-raw, channels=(int)5000", "EMPTY"); /* Now add filters */ /* Formats not acceptable */ run_getcaps_check_from_strings ("audio/x-opus, rate=(int)1000", NULL, "EMPTY"); run_getcaps_check_from_strings ("audio/x-opus, channels=(int)200", NULL, "EMPTY"); /* Should restrict the result of the caps query to the selected rate/channels */ run_getcaps_check_from_strings ("audio/x-opus, rate=(int)8000", NULL, "audio/x-opus, rate=(int)8000, channels=(int)[1,8]"); run_getcaps_check_from_strings ("audio/x-opus, channels=(int)2", NULL, "audio/x-opus, rate=(int){48000, 24000, 16000, 12000, 8000}, channels=(int)2"); } GST_END_TEST; GST_START_TEST (test_opus_decode_plc_timestamps_with_fec) { GstBuffer *buf; GstHarness *h = gst_harness_new_parse ("opusdec use-inband-fec=TRUE plc=TRUE"); GstClockTime dur0 = GST_MSECOND * 35 / 10; /* because of lookahead */ GstClockTime dur = GST_MSECOND * 10; gst_harness_add_src_parse (h, "audiotestsrc samplesperbuffer=480 is-live=TRUE ! " "opusenc frame-size=10 inband-fec=TRUE", TRUE); /* Push first buffer from encoder to decoder. It will not be decoded yet * because of the delay introduced by FEC */ gst_harness_src_crank_and_push_many (h, 1, 1); fail_unless_equals_int (0, gst_harness_buffers_received (h)); /* Drop second buffer from encoder and send a GAP event to decoder * instead with 2x duration */ gst_harness_src_crank_and_push_many (h, 1, 0); fail_unless (buf = gst_harness_pull (h->src_harness)); fail_unless (gst_harness_push_event (h, gst_event_new_gap (GST_BUFFER_PTS (buf), GST_BUFFER_DURATION (buf) * 2))); gst_buffer_unref (buf); /* Extract first buffer from decoder and verify timstamps */ fail_unless (buf = gst_harness_pull (h)); fail_unless_equals_int64 (0, GST_BUFFER_PTS (buf)); fail_unless_equals_int64 (dur0, GST_BUFFER_DURATION (buf)); fail_unless (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)); gst_buffer_unref (buf); /* Third buffer is pushed from encoder to decoder with DISCONT set */ gst_harness_src_crank_and_push_many (h, 1, 0); fail_unless (buf = gst_harness_pull (h->src_harness)); GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT); gst_harness_push (h, buf); /* Extract second (concealed) buffer from decoder and verify timestamp and the 2x duration */ fail_unless (buf = gst_harness_pull (h)); fail_unless_equals_int64 (dur0, GST_BUFFER_PTS (buf)); fail_unless_equals_int64 (dur * 2, GST_BUFFER_DURATION (buf)); fail_if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)); gst_buffer_unref (buf); /* Push fourth buffer from encoder to decoder as normal */ gst_harness_src_crank_and_push_many (h, 1, 1); /* Extract third buffer from decoder and verify timestamps */ fail_unless (buf = gst_harness_pull (h)); fail_unless_equals_int64 (dur0 + 1 * dur, GST_BUFFER_PTS (buf)); fail_unless_equals_int64 (dur, GST_BUFFER_DURATION (buf)); fail_if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)); gst_buffer_unref (buf); gst_harness_teardown (h); } GST_END_TEST; static Suite * opus_suite (void) { Suite *s = suite_create ("opus"); TCase *tc_chain = tcase_create ("general"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, test_opus_encode_nothing); tcase_add_test (tc_chain, test_opus_decode_nothing); tcase_add_test (tc_chain, test_opus_encode_samples); tcase_add_test (tc_chain, test_opus_encode_properties); tcase_add_test (tc_chain, test_opusdec_getcaps); tcase_add_test (tc_chain, test_opus_decode_plc_timestamps_with_fec); return s; } GST_CHECK_MAIN (opus);
apache-2.0
jimczi/elasticsearch
core/src/main/java/org/elasticsearch/search/aggregations/pipeline/cumulativesum/CumulativeSumPipelineAggregationBuilder.java
8250
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.pipeline.cumulativesum; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.aggregations.AggregatorFactory; import org.elasticsearch.search.aggregations.PipelineAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregatorFactory; import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregatorFactory; import org.elasticsearch.search.aggregations.pipeline.AbstractPipelineAggregationBuilder; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.BucketMetricsParser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.BUCKETS_PATH; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.FORMAT; public class CumulativeSumPipelineAggregationBuilder extends AbstractPipelineAggregationBuilder<CumulativeSumPipelineAggregationBuilder> { public static final String NAME = "cumulative_sum"; private String format; public CumulativeSumPipelineAggregationBuilder(String name, String bucketsPath) { super(name, NAME, new String[] { bucketsPath }); } /** * Read from a stream. */ public CumulativeSumPipelineAggregationBuilder(StreamInput in) throws IOException { super(in, NAME); format = in.readOptionalString(); } @Override protected final void doWriteTo(StreamOutput out) throws IOException { out.writeOptionalString(format); } /** * Sets the format to use on the output of this aggregation. */ public CumulativeSumPipelineAggregationBuilder format(String format) { if (format == null) { throw new IllegalArgumentException("[format] must not be null: [" + name + "]"); } this.format = format; return this; } /** * Gets the format to use on the output of this aggregation. */ public String format() { return format; } protected DocValueFormat formatter() { if (format != null) { return new DocValueFormat.Decimal(format); } else { return DocValueFormat.RAW; } } @Override protected PipelineAggregator createInternal(Map<String, Object> metaData) throws IOException { return new CumulativeSumPipelineAggregator(name, bucketsPaths, formatter(), metaData); } @Override public void doValidate(AggregatorFactory<?> parent, AggregatorFactory<?>[] aggFactories, List<PipelineAggregationBuilder> pipelineAggregatorFactories) { if (bucketsPaths.length != 1) { throw new IllegalStateException(BUCKETS_PATH.getPreferredName() + " must contain a single entry for aggregation [" + name + "]"); } if (parent instanceof HistogramAggregatorFactory) { HistogramAggregatorFactory histoParent = (HistogramAggregatorFactory) parent; if (histoParent.minDocCount() != 0) { throw new IllegalStateException("parent histogram of cumulative sum aggregation [" + name + "] must have min_doc_count of 0"); } } else if (parent instanceof DateHistogramAggregatorFactory) { DateHistogramAggregatorFactory histoParent = (DateHistogramAggregatorFactory) parent; if (histoParent.minDocCount() != 0) { throw new IllegalStateException("parent histogram of cumulative sum aggregation [" + name + "] must have min_doc_count of 0"); } } else { throw new IllegalStateException("cumulative sum aggregation [" + name + "] must have a histogram or date_histogram as parent"); } } @Override protected final XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException { if (format != null) { builder.field(BucketMetricsParser.FORMAT.getPreferredName(), format); } return builder; } public static CumulativeSumPipelineAggregationBuilder parse(String pipelineAggregatorName, XContentParser parser) throws IOException { XContentParser.Token token; String currentFieldName = null; String[] bucketsPaths = null; String format = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if (FORMAT.match(currentFieldName)) { format = parser.text(); } else if (BUCKETS_PATH.match(currentFieldName)) { bucketsPaths = new String[] { parser.text() }; } else { throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_ARRAY) { if (BUCKETS_PATH.match(currentFieldName)) { List<String> paths = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { String path = parser.text(); paths.add(path); } bucketsPaths = paths.toArray(new String[paths.size()]); } else { throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "]."); } } else { throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " in [" + pipelineAggregatorName + "]."); } } if (bucketsPaths == null) { throw new ParsingException(parser.getTokenLocation(), "Missing required field [" + BUCKETS_PATH.getPreferredName() + "] for derivative aggregation [" + pipelineAggregatorName + "]"); } CumulativeSumPipelineAggregationBuilder factory = new CumulativeSumPipelineAggregationBuilder(pipelineAggregatorName, bucketsPaths[0]); if (format != null) { factory.format(format); } return factory; } @Override protected int doHashCode() { return Objects.hash(format); } @Override protected boolean doEquals(Object obj) { CumulativeSumPipelineAggregationBuilder other = (CumulativeSumPipelineAggregationBuilder) obj; return Objects.equals(format, other.format); } @Override public String getWriteableName() { return NAME; } }
apache-2.0
queeniema/incubator-edgent-website
site/javadoc/r1.1.0/org/apache/edgent/analytics/sensors/package-use.html
8634
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Sun Feb 26 17:08:13 EST 2017 --> <title>Uses of Package org.apache.edgent.analytics.sensors (Edgent v1.1.0)</title> <meta name="date" content="2017-02-26"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.apache.edgent.analytics.sensors (Edgent v1.1.0)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/edgent/analytics/sensors/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package org.apache.edgent.analytics.sensors" class="title">Uses of Package<br>org.apache.edgent.analytics.sensors</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/edgent/analytics/sensors/package-summary.html">org.apache.edgent.analytics.sensors</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.edgent.analytics.sensors">org.apache.edgent.analytics.sensors</a></td> <td class="colLast"> <div class="block">Analytics focused on handling sensor data.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.apache.edgent.samples.apps">org.apache.edgent.samples.apps</a></td> <td class="colLast"> <div class="block">Support for some more complex Edgent application samples.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.edgent.samples.utils.sensor">org.apache.edgent.samples.utils.sensor</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.edgent.analytics.sensors"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/apache/edgent/analytics/sensors/package-summary.html">org.apache.edgent.analytics.sensors</a> used by <a href="../../../../../org/apache/edgent/analytics/sensors/package-summary.html">org.apache.edgent.analytics.sensors</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../org/apache/edgent/analytics/sensors/class-use/Range.html#org.apache.edgent.analytics.sensors">Range</a> <div class="block">A generic immutable range of values and a way to check a value for containment in the range.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../org/apache/edgent/analytics/sensors/class-use/Range.BoundType.html#org.apache.edgent.analytics.sensors">Range.BoundType</a> <div class="block">Exclude or include an endpoint value in the range.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.edgent.samples.apps"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/apache/edgent/analytics/sensors/package-summary.html">org.apache.edgent.analytics.sensors</a> used by <a href="../../../../../org/apache/edgent/samples/apps/package-summary.html">org.apache.edgent.samples.apps</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../org/apache/edgent/analytics/sensors/class-use/Range.html#org.apache.edgent.samples.apps">Range</a> <div class="block">A generic immutable range of values and a way to check a value for containment in the range.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.edgent.samples.utils.sensor"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../org/apache/edgent/analytics/sensors/package-summary.html">org.apache.edgent.analytics.sensors</a> used by <a href="../../../../../org/apache/edgent/samples/utils/sensor/package-summary.html">org.apache.edgent.samples.utils.sensor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../org/apache/edgent/analytics/sensors/class-use/Range.html#org.apache.edgent.samples.utils.sensor">Range</a> <div class="block">A generic immutable range of values and a way to check a value for containment in the range.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><a href="http://edgent.incubator.apache.org">Apache Edgent (incubating)</a></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/edgent/analytics/sensors/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 The Apache Software Foundation. All Rights Reserved - 4744f56-20170226-1707</small></p> </body> </html>
apache-2.0
putcn/Paddle
paddle/math/PoolAllocator.cpp
2187
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "PoolAllocator.h" namespace paddle { PoolAllocator::PoolAllocator(Allocator* allocator, size_t sizeLimit, const std::string& name) : allocator_(allocator), sizeLimit_(sizeLimit), poolMemorySize_(0), name_(name) {} PoolAllocator::~PoolAllocator() { freeAll(); } void* PoolAllocator::alloc(size_t size) { if (sizeLimit_ > 0) { std::lock_guard<std::mutex> guard(mutex_); auto it = pool_.find(size); if (it == pool_.end() || it->second.size() == 0) { if (poolMemorySize_ >= sizeLimit_) { freeAll(); } return allocator_->alloc(size); } else { auto buf = it->second.back(); it->second.pop_back(); poolMemorySize_ -= size; return buf; } } else { return allocator_->alloc(size); } } void PoolAllocator::free(void* ptr, size_t size) { if (sizeLimit_ > 0) { std::lock_guard<std::mutex> guard(mutex_); auto& it = pool_[size]; it.push_back(ptr); poolMemorySize_ += size; } else { allocator_->free(ptr); } } void PoolAllocator::freeAll() { for (auto it : pool_) { for (auto ptr : it.second) { allocator_->free(ptr); } } poolMemorySize_ = 0; pool_.clear(); } void PoolAllocator::printAll() { size_t memory = 0; LOG(INFO) << name_ << ":"; for (auto it : pool_) { LOG(INFO) << " size:" << it.first; for (auto ptr : it.second) { LOG(INFO) << " ptr:" << ptr; memory += it.first; } } LOG(INFO) << "memory size: " << memory; } } // namespace paddle
apache-2.0
shouhong/kubernetes
pkg/registry/rbac/rest/storage_rbac.go
8272
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package rest import ( "fmt" "sync" "time" "github.com/golang/glog" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/registry/rest" genericapiserver "k8s.io/apiserver/pkg/server" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" rbacapiv1alpha1 "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1" rbacapiv1beta1 "k8s.io/kubernetes/pkg/apis/rbac/v1beta1" rbacclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/internalversion" "k8s.io/kubernetes/pkg/registry/rbac/clusterrole" clusterrolepolicybased "k8s.io/kubernetes/pkg/registry/rbac/clusterrole/policybased" clusterrolestore "k8s.io/kubernetes/pkg/registry/rbac/clusterrole/storage" "k8s.io/kubernetes/pkg/registry/rbac/clusterrolebinding" clusterrolebindingpolicybased "k8s.io/kubernetes/pkg/registry/rbac/clusterrolebinding/policybased" clusterrolebindingstore "k8s.io/kubernetes/pkg/registry/rbac/clusterrolebinding/storage" "k8s.io/kubernetes/pkg/registry/rbac/role" rolepolicybased "k8s.io/kubernetes/pkg/registry/rbac/role/policybased" rolestore "k8s.io/kubernetes/pkg/registry/rbac/role/storage" "k8s.io/kubernetes/pkg/registry/rbac/rolebinding" rolebindingpolicybased "k8s.io/kubernetes/pkg/registry/rbac/rolebinding/policybased" rolebindingstore "k8s.io/kubernetes/pkg/registry/rbac/rolebinding/storage" rbacregistryvalidation "k8s.io/kubernetes/pkg/registry/rbac/validation" "k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/bootstrappolicy" ) type RESTStorageProvider struct { Authorizer authorizer.Authorizer } var _ genericapiserver.PostStartHookProvider = RESTStorageProvider{} func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(rbac.GroupName, api.Registry, api.Scheme, api.ParameterCodec, api.Codecs) if apiResourceConfigSource.AnyResourcesForVersionEnabled(rbacapiv1alpha1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[rbacapiv1alpha1.SchemeGroupVersion.Version] = p.storage(rbacapiv1alpha1.SchemeGroupVersion, apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = rbacapiv1alpha1.SchemeGroupVersion } if apiResourceConfigSource.AnyResourcesForVersionEnabled(rbacapiv1beta1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[rbacapiv1beta1.SchemeGroupVersion.Version] = p.storage(rbacapiv1beta1.SchemeGroupVersion, apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = rbacapiv1beta1.SchemeGroupVersion } return apiGroupInfo, true } func (p RESTStorageProvider) storage(version schema.GroupVersion, apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage { once := new(sync.Once) var ( authorizationRuleResolver rbacregistryvalidation.AuthorizationRuleResolver rolesStorage rest.StandardStorage roleBindingsStorage rest.StandardStorage clusterRolesStorage rest.StandardStorage clusterRoleBindingsStorage rest.StandardStorage ) initializeStorage := func() { once.Do(func() { rolesStorage = rolestore.NewREST(restOptionsGetter) roleBindingsStorage = rolebindingstore.NewREST(restOptionsGetter) clusterRolesStorage = clusterrolestore.NewREST(restOptionsGetter) clusterRoleBindingsStorage = clusterrolebindingstore.NewREST(restOptionsGetter) authorizationRuleResolver = rbacregistryvalidation.NewDefaultRuleResolver( role.AuthorizerAdapter{Registry: role.NewRegistry(rolesStorage)}, rolebinding.AuthorizerAdapter{Registry: rolebinding.NewRegistry(roleBindingsStorage)}, clusterrole.AuthorizerAdapter{Registry: clusterrole.NewRegistry(clusterRolesStorage)}, clusterrolebinding.AuthorizerAdapter{Registry: clusterrolebinding.NewRegistry(clusterRoleBindingsStorage)}, ) }) } storage := map[string]rest.Storage{} if apiResourceConfigSource.ResourceEnabled(version.WithResource("roles")) { initializeStorage() storage["roles"] = rolepolicybased.NewStorage(rolesStorage, authorizationRuleResolver) } if apiResourceConfigSource.ResourceEnabled(version.WithResource("rolebindings")) { initializeStorage() storage["rolebindings"] = rolebindingpolicybased.NewStorage(roleBindingsStorage, p.Authorizer, authorizationRuleResolver) } if apiResourceConfigSource.ResourceEnabled(version.WithResource("clusterroles")) { initializeStorage() storage["clusterroles"] = clusterrolepolicybased.NewStorage(clusterRolesStorage, authorizationRuleResolver) } if apiResourceConfigSource.ResourceEnabled(version.WithResource("clusterrolebindings")) { initializeStorage() storage["clusterrolebindings"] = clusterrolebindingpolicybased.NewStorage(clusterRoleBindingsStorage, p.Authorizer, authorizationRuleResolver) } return storage } func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error) { return "rbac/bootstrap-roles", PostStartHook, nil } func PostStartHook(hookContext genericapiserver.PostStartHookContext) error { // intializing roles is really important. On some e2e runs, we've seen cases where etcd is down when the server // starts, the roles don't initialize, and nothing works. err := wait.Poll(1*time.Second, 30*time.Second, func() (done bool, err error) { clientset, err := rbacclient.NewForConfig(hookContext.LoopbackClientConfig) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return false, nil } existingClusterRoles, err := clientset.ClusterRoles().List(metav1.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return false, nil } // only initialized on empty etcd if len(existingClusterRoles.Items) == 0 { for _, clusterRole := range append(bootstrappolicy.ClusterRoles(), bootstrappolicy.ControllerRoles()...) { if _, err := clientset.ClusterRoles().Create(&clusterRole); err != nil { // don't fail on failures, try to create as many as you can utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) continue } glog.Infof("Created clusterrole.%s/%s", rbac.GroupName, clusterRole.Name) } } existingClusterRoleBindings, err := clientset.ClusterRoleBindings().List(metav1.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterrolebindings: %v", err)) return false, nil } // only initialized on empty etcd if len(existingClusterRoleBindings.Items) == 0 { for _, clusterRoleBinding := range append(bootstrappolicy.ClusterRoleBindings(), bootstrappolicy.ControllerRoleBindings()...) { if _, err := clientset.ClusterRoleBindings().Create(&clusterRoleBinding); err != nil { // don't fail on failures, try to create as many as you can utilruntime.HandleError(fmt.Errorf("unable to initialize clusterrolebindings: %v", err)) continue } glog.Infof("Created clusterrolebinding.%s/%s", rbac.GroupName, clusterRoleBinding.Name) } } return true, nil }) // if we're never able to make it through intialization, kill the API server if err != nil { return fmt.Errorf("unable to initialize roles: %v", err) } return nil } func (p RESTStorageProvider) GroupName() string { return rbac.GroupName }
apache-2.0
GlenRSmith/elasticsearch
x-pack/plugin/autoscaling/src/main/java/org/elasticsearch/xpack/autoscaling/storage/ReactiveStorageDeciderService.java
34193
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.autoscaling.storage; import org.elasticsearch.cluster.ClusterInfo; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.DiskUsage; import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.DataStreamMetadata; import org.elasticsearch.cluster.metadata.IndexAbstraction; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeFilters; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.allocation.DataTier; import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders; import org.elasticsearch.cluster.routing.allocation.decider.Decision; import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider; import org.elasticsearch.cluster.routing.allocation.decider.FilterAllocationDecider; import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationDecider; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.Tuple; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.snapshots.SnapshotShardSizeInfo; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingCapacity; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderContext; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderResult; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderService; import org.elasticsearch.xpack.cluster.routing.allocation.DataTierAllocationDecider; import java.io.IOException; import java.math.BigInteger; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class ReactiveStorageDeciderService implements AutoscalingDeciderService { public static final String NAME = "reactive_storage"; private final DiskThresholdSettings diskThresholdSettings; private final DataTierAllocationDecider dataTierAllocationDecider; private final AllocationDeciders allocationDeciders; public ReactiveStorageDeciderService(Settings settings, ClusterSettings clusterSettings, AllocationDeciders allocationDeciders) { this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterSettings); this.dataTierAllocationDecider = new DataTierAllocationDecider(); this.allocationDeciders = allocationDeciders; } @Override public String name() { return NAME; } @Override public List<Setting<?>> deciderSettings() { return List.of(); } @Override public List<DiscoveryNodeRole> roles() { return List.of( DiscoveryNodeRole.DATA_ROLE, DiscoveryNodeRole.DATA_CONTENT_NODE_ROLE, DiscoveryNodeRole.DATA_HOT_NODE_ROLE, DiscoveryNodeRole.DATA_WARM_NODE_ROLE, DiscoveryNodeRole.DATA_COLD_NODE_ROLE ); } @Override public AutoscalingDeciderResult scale(Settings configuration, AutoscalingDeciderContext context) { AutoscalingCapacity autoscalingCapacity = context.currentCapacity(); if (autoscalingCapacity == null || autoscalingCapacity.total().storage() == null) { return new AutoscalingDeciderResult(null, new ReactiveReason("current capacity not available", -1, -1)); } AllocationState allocationState = new AllocationState( context, diskThresholdSettings, allocationDeciders, dataTierAllocationDecider ); long unassignedBytes = allocationState.storagePreventsAllocation(); long assignedBytes = allocationState.storagePreventsRemainOrMove(); long maxShardSize = allocationState.maxShardSize(); assert assignedBytes >= 0; assert unassignedBytes >= 0; assert maxShardSize >= 0; String message = message(unassignedBytes, assignedBytes); AutoscalingCapacity requiredCapacity = AutoscalingCapacity.builder() .total(autoscalingCapacity.total().storage().getBytes() + unassignedBytes + assignedBytes, null) .node(maxShardSize, null) .build(); return new AutoscalingDeciderResult(requiredCapacity, new ReactiveReason(message, unassignedBytes, assignedBytes)); } static String message(long unassignedBytes, long assignedBytes) { return unassignedBytes > 0 || assignedBytes > 0 ? "not enough storage available, needs " + new ByteSizeValue(unassignedBytes + assignedBytes) : "storage ok"; } static boolean isDiskOnlyNoDecision(Decision decision) { return singleNoDecision(decision, single -> true).map(DiskThresholdDecider.NAME::equals).orElse(false); } static boolean isFilterTierOnlyDecision(Decision decision, IndexMetadata indexMetadata) { // only primary shards are handled here, allowing us to disregard same shard allocation decider. return singleNoDecision(decision, single -> SameShardAllocationDecider.NAME.equals(single.label()) == false).filter( FilterAllocationDecider.NAME::equals ).map(d -> filterLooksLikeTier(indexMetadata)).orElse(false); } static boolean filterLooksLikeTier(IndexMetadata indexMetadata) { return isOnlyAttributeValueFilter(indexMetadata.requireFilters()) && isOnlyAttributeValueFilter(indexMetadata.includeFilters()) && isOnlyAttributeValueFilter(indexMetadata.excludeFilters()); } private static boolean isOnlyAttributeValueFilter(DiscoveryNodeFilters filters) { if (filters == null) { return true; } else { return DiscoveryNodeFilters.trimTier(filters).isOnlyAttributeValueFilter(); } } static Optional<String> singleNoDecision(Decision decision, Predicate<Decision> predicate) { List<Decision> nos = decision.getDecisions() .stream() .filter(single -> single.type() == Decision.Type.NO) .filter(predicate) .collect(Collectors.toList()); if (nos.size() == 1) { return Optional.ofNullable(nos.get(0).label()); } else { return Optional.empty(); } } // todo: move this to top level class. public static class AllocationState { private final ClusterState state; private final AllocationDeciders allocationDeciders; private final DataTierAllocationDecider dataTierAllocationDecider; private final DiskThresholdSettings diskThresholdSettings; private final ClusterInfo info; private final SnapshotShardSizeInfo shardSizeInfo; private final Predicate<DiscoveryNode> nodeTierPredicate; private final Set<DiscoveryNode> nodes; private final Set<String> nodeIds; private final Set<DiscoveryNodeRole> roles; AllocationState( AutoscalingDeciderContext context, DiskThresholdSettings diskThresholdSettings, AllocationDeciders allocationDeciders, DataTierAllocationDecider dataTierAllocationDecider ) { this( context.state(), allocationDeciders, dataTierAllocationDecider, diskThresholdSettings, context.info(), context.snapshotShardSizeInfo(), context.nodes(), context.roles() ); } AllocationState( ClusterState state, AllocationDeciders allocationDeciders, DataTierAllocationDecider dataTierAllocationDecider, DiskThresholdSettings diskThresholdSettings, ClusterInfo info, SnapshotShardSizeInfo shardSizeInfo, Set<DiscoveryNode> nodes, Set<DiscoveryNodeRole> roles ) { this.state = state; this.allocationDeciders = allocationDeciders; this.dataTierAllocationDecider = dataTierAllocationDecider; this.diskThresholdSettings = diskThresholdSettings; this.info = info; this.shardSizeInfo = shardSizeInfo; this.nodes = nodes; this.nodeIds = nodes.stream().map(DiscoveryNode::getId).collect(Collectors.toSet()); this.nodeTierPredicate = nodes::contains; this.roles = roles; } public long storagePreventsAllocation() { RoutingAllocation allocation = new RoutingAllocation( allocationDeciders, state.getRoutingNodes(), state, info, shardSizeInfo, System.nanoTime() ); return StreamSupport.stream(state.getRoutingNodes().unassigned().spliterator(), false) .filter(shard -> canAllocate(shard, allocation) == false) .filter(shard -> cannotAllocateDueToStorage(shard, allocation)) .mapToLong(this::sizeOf) .sum(); } public long storagePreventsRemainOrMove() { RoutingAllocation allocation = new RoutingAllocation( allocationDeciders, state.getRoutingNodes(), state, info, shardSizeInfo, System.nanoTime() ); List<ShardRouting> candidates = new LinkedList<>(); for (RoutingNode routingNode : state.getRoutingNodes()) { for (ShardRouting shard : routingNode) { if (shard.started() && canRemainOnlyHighestTierPreference(shard, allocation) == false && canAllocate(shard, allocation) == false) { candidates.add(shard); } } } // track these to ensure we do not double account if they both cannot remain and allocated due to storage. Set<ShardRouting> unmovableShards = candidates.stream() .filter(s -> allocatedToTier(s, allocation)) .filter(s -> cannotRemainDueToStorage(s, allocation)) .collect(Collectors.toSet()); long unmovableBytes = unmovableShards.stream() .collect(Collectors.groupingBy(ShardRouting::currentNodeId)) .entrySet() .stream() .mapToLong(e -> unmovableSize(e.getKey(), e.getValue())) .sum(); long unallocatableBytes = candidates.stream() .filter(Predicate.not(unmovableShards::contains)) .filter(s1 -> cannotAllocateDueToStorage(s1, allocation)) .mapToLong(this::sizeOf) .sum(); return unallocatableBytes + unmovableBytes; } /** * Check if shard can remain where it is, with the additional check that the DataTierAllocationDecider did not allow it to stay * on a node in a lower preference tier. */ public boolean canRemainOnlyHighestTierPreference(ShardRouting shard, RoutingAllocation allocation) { boolean result = allocationDeciders.canRemain( shard, allocation.routingNodes().node(shard.currentNodeId()), allocation ) != Decision.NO; if (result && nodes.isEmpty() && Strings.hasText(DataTier.TIER_PREFERENCE_SETTING.get(indexMetadata(shard, allocation).getSettings()))) { // The data tier decider allows a shard to remain on a lower preference tier when no nodes exists on higher preference // tiers. // Here we ensure that if our policy governs the highest preference tier, we assume the shard needs to move to that tier // once a node is started for it. // In the case of overlapping policies, this is consistent with double accounting of unassigned. return isAssignedToTier(shard, allocation) == false; } return result; } private boolean allocatedToTier(ShardRouting s, RoutingAllocation allocation) { return nodeTierPredicate.test(allocation.routingNodes().node(s.currentNodeId()).node()); } /** * Check that disk decider is only decider for a node preventing allocation of the shard. * @return true if and only if a node exists in the tier where only disk decider prevents allocation */ private boolean cannotAllocateDueToStorage(ShardRouting shard, RoutingAllocation allocation) { if (nodeIds.isEmpty() && needsThisTier(shard, allocation)) { return true; } assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { return nodesInTier(allocation.routingNodes()).map(node -> allocationDeciders.canAllocate(shard, node, allocation)) .anyMatch(ReactiveStorageDeciderService::isDiskOnlyNoDecision); } finally { allocation.debugDecision(false); } } /** * Check that the disk decider is only decider that says NO to let shard remain on current node. * @return true if and only if disk decider is only decider that says NO to canRemain. */ private boolean cannotRemainDueToStorage(ShardRouting shard, RoutingAllocation allocation) { assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { return isDiskOnlyNoDecision( allocationDeciders.canRemain(shard, allocation.routingNodes().node(shard.currentNodeId()), allocation) ); } finally { allocation.debugDecision(false); } } private boolean canAllocate(ShardRouting shard, RoutingAllocation allocation) { return nodesInTier(allocation.routingNodes()).anyMatch( node -> allocationDeciders.canAllocate(shard, node, allocation) != Decision.NO ); } boolean needsThisTier(ShardRouting shard, RoutingAllocation allocation) { if (isAssignedToTier(shard, allocation) == false) { return false; } IndexMetadata indexMetadata = indexMetadata(shard, allocation); Set<Decision.Type> decisionTypes = StreamSupport.stream(allocation.routingNodes().spliterator(), false) .map( node -> dataTierAllocationDecider.shouldFilter( indexMetadata, node.node().getRoles(), this::highestPreferenceTier, allocation ) ) .map(Decision::type) .collect(Collectors.toSet()); if (decisionTypes.contains(Decision.Type.NO)) { // we know we have some filter and can respond. Only need this tier if ALL responses where NO. return decisionTypes.size() == 1; } // check for using allocation filters for data tiers. For simplicity, only scale up new tier based on primary shard if (shard.primary() == false) { return false; } assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { // check that it does not belong on any existing node, i.e., there must be only a tier like reason it cannot be allocated return StreamSupport.stream(allocation.routingNodes().spliterator(), false) .anyMatch(node -> isFilterTierOnlyDecision(allocationDeciders.canAllocate(shard, node, allocation), indexMetadata)); } finally { allocation.debugDecision(false); } } private boolean isAssignedToTier(ShardRouting shard, RoutingAllocation allocation) { IndexMetadata indexMetadata = indexMetadata(shard, allocation); return dataTierAllocationDecider.shouldFilter(indexMetadata, roles, this::highestPreferenceTier, allocation) != Decision.NO; } private IndexMetadata indexMetadata(ShardRouting shard, RoutingAllocation allocation) { return allocation.metadata().getIndexSafe(shard.index()); } private Optional<String> highestPreferenceTier(List<String> preferredTiers, DiscoveryNodes unused) { assert preferredTiers.isEmpty() == false; return Optional.of(preferredTiers.get(0)); } public long maxShardSize() { return nodesInTier(state.getRoutingNodes()).flatMap(rn -> StreamSupport.stream(rn.spliterator(), false)) .mapToLong(this::sizeOf) .max() .orElse(0L); } long sizeOf(ShardRouting shard) { long expectedShardSize = getExpectedShardSize(shard); if (expectedShardSize == 0L && shard.primary() == false) { ShardRouting primary = state.getRoutingNodes().activePrimary(shard.shardId()); if (primary != null) { expectedShardSize = getExpectedShardSize(primary); } } assert expectedShardSize >= 0; // todo: we should ideally not have the level of uncertainty we have here. return expectedShardSize == 0L ? ByteSizeUnit.KB.toBytes(1) : expectedShardSize; } private long getExpectedShardSize(ShardRouting shard) { return DiskThresholdDecider.getExpectedShardSize(shard, 0L, info, shardSizeInfo, state.metadata(), state.routingTable()); } long unmovableSize(String nodeId, Collection<ShardRouting> shards) { ClusterInfo clusterInfo = this.info; DiskUsage diskUsage = clusterInfo.getNodeMostAvailableDiskUsages().get(nodeId); if (diskUsage == null) { // do not want to scale up then, since this should only happen when node has just joined (clearly edge case). return 0; } long threshold = Math.max( diskThresholdSettings.getFreeBytesThresholdHigh().getBytes(), thresholdFromPercentage(diskThresholdSettings.getFreeDiskThresholdHigh(), diskUsage) ); long missing = threshold - diskUsage.getFreeBytes(); return Math.max(missing, shards.stream().mapToLong(this::sizeOf).min().orElseThrow()); } private long thresholdFromPercentage(Double percentage, DiskUsage diskUsage) { if (percentage == null) { return 0L; } return (long) Math.ceil(diskUsage.getTotalBytes() * percentage / 100); } Stream<RoutingNode> nodesInTier(RoutingNodes routingNodes) { return nodeIds.stream().map(n -> routingNodes.node(n)); } private static class SingleForecast { private final Map<IndexMetadata, Long> additionalIndices; private final DataStream updatedDataStream; private SingleForecast(Map<IndexMetadata, Long> additionalIndices, DataStream updatedDataStream) { this.additionalIndices = additionalIndices; this.updatedDataStream = updatedDataStream; } public void applyRouting(RoutingTable.Builder routing) { additionalIndices.keySet().forEach(routing::addAsNew); } public void applyMetadata(Metadata.Builder metadataBuilder) { additionalIndices.keySet().forEach(imd -> metadataBuilder.put(imd, false)); metadataBuilder.put(updatedDataStream); } public void applySize(ImmutableOpenMap.Builder<String, Long> builder, RoutingTable updatedRoutingTable) { for (Map.Entry<IndexMetadata, Long> entry : additionalIndices.entrySet()) { List<ShardRouting> shardRoutings = updatedRoutingTable.allShards(entry.getKey().getIndex().getName()); long size = entry.getValue() / shardRoutings.size(); shardRoutings.forEach(s -> builder.put(ClusterInfo.shardIdentifierFromRouting(s), size)); } } } public AllocationState forecast(long forecastWindow, long now) { if (forecastWindow == 0) { return this; } // for now we only look at data-streams. We might want to also detect alias based time-based indices. DataStreamMetadata dataStreamMetadata = state.metadata().custom(DataStreamMetadata.TYPE); if (dataStreamMetadata == null) { return this; } List<SingleForecast> singleForecasts = dataStreamMetadata.dataStreams() .keySet() .stream() .map(state.metadata().getIndicesLookup()::get) .map(IndexAbstraction.DataStream.class::cast) .map(ds -> forecast(state.metadata(), ds, forecastWindow, now)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (singleForecasts.isEmpty()) { return this; } Metadata.Builder metadataBuilder = Metadata.builder(state.metadata()); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(state.routingTable()); ImmutableOpenMap.Builder<String, Long> sizeBuilder = ImmutableOpenMap.builder(); singleForecasts.forEach(p -> p.applyMetadata(metadataBuilder)); singleForecasts.forEach(p -> p.applyRouting(routingTableBuilder)); RoutingTable routingTable = routingTableBuilder.build(); singleForecasts.forEach(p -> p.applySize(sizeBuilder, routingTable)); ClusterState forecastClusterState = ClusterState.builder(state).metadata(metadataBuilder).routingTable(routingTable).build(); ClusterInfo forecastInfo = new ExtendedClusterInfo(sizeBuilder.build(), AllocationState.this.info); return new AllocationState( forecastClusterState, allocationDeciders, dataTierAllocationDecider, diskThresholdSettings, forecastInfo, shardSizeInfo, nodes, roles ); } private SingleForecast forecast(Metadata metadata, IndexAbstraction.DataStream stream, long forecastWindow, long now) { List<Index> indices = stream.getIndices(); if (dataStreamAllocatedToNodes(metadata, indices) == false) return null; long minCreationDate = Long.MAX_VALUE; long totalSize = 0; int count = 0; while (count < indices.size()) { ++count; IndexMetadata indexMetadata = metadata.index(indices.get(indices.size() - count)); long creationDate = indexMetadata.getCreationDate(); if (creationDate < 0) { return null; } minCreationDate = Math.min(minCreationDate, creationDate); totalSize += state.getRoutingTable().allShards(indexMetadata.getIndex().getName()).stream().mapToLong(this::sizeOf).sum(); // we terminate loop after collecting data to ensure we consider at least the forecast window (and likely some more). if (creationDate <= now - forecastWindow) { break; } } if (totalSize == 0) { return null; } // round up long avgSizeCeil = (totalSize - 1) / count + 1; long actualWindow = now - minCreationDate; if (actualWindow == 0) { return null; } // rather than simulate rollover, we copy the index meta data and do minimal adjustments. long scaledTotalSize; int numberNewIndices; if (actualWindow > forecastWindow) { scaledTotalSize = BigInteger.valueOf(totalSize) .multiply(BigInteger.valueOf(forecastWindow)) .divide(BigInteger.valueOf(actualWindow)) .longValueExact(); // round up numberNewIndices = (int) Math.min((scaledTotalSize - 1) / avgSizeCeil + 1, indices.size()); if (scaledTotalSize == 0) { return null; } } else { numberNewIndices = count; scaledTotalSize = totalSize; } IndexMetadata writeIndex = metadata.index(stream.getWriteIndex()); Map<IndexMetadata, Long> newIndices = new HashMap<>(); DataStream dataStream = stream.getDataStream(); for (int i = 0; i < numberNewIndices; ++i) { final String uuid = UUIDs.randomBase64UUID(); final Tuple<String, Long> dummyRolledDatastream = dataStream.nextWriteIndexAndGeneration(state.metadata()); dataStream = dataStream.rollover(new Index(dummyRolledDatastream.v1(), uuid), dummyRolledDatastream.v2()); // this unintentionally copies the in-sync allocation ids too. This has the fortunate effect of these indices // not being regarded new by the disk threshold decider, thereby respecting the low watermark threshold even for primaries. // This is highly desirable so fixing this to clear the in-sync allocation ids will require a more elaborate solution, // ensuring at least that when replicas are involved, we still respect the low watermark. This is therefore left as is // for now with the intention to fix in a follow-up. IndexMetadata newIndex = IndexMetadata.builder(writeIndex) .index(dataStream.getWriteIndex().getName()) .settings(Settings.builder().put(writeIndex.getSettings()).put(IndexMetadata.SETTING_INDEX_UUID, uuid)) .build(); long size = Math.min(avgSizeCeil, scaledTotalSize - (avgSizeCeil * i)); assert size > 0; newIndices.put(newIndex, size); } return new SingleForecast(newIndices, dataStream); } /** * Check that at least one shard is on the set of nodes. If they are all unallocated, we do not want to make any prediction to not * hit the wrong policy. * @param indices the indices of the data stream, in original order from data stream meta. * @return true if the first allocated index is allocated only to the set of nodes. */ private boolean dataStreamAllocatedToNodes(Metadata metadata, List<Index> indices) { for (int i = 0; i < indices.size(); ++i) { IndexMetadata indexMetadata = metadata.index(indices.get(indices.size() - i - 1)); Set<Boolean> inNodes = state.getRoutingTable() .allShards(indexMetadata.getIndex().getName()) .stream() .map(ShardRouting::currentNodeId) .filter(Objects::nonNull) .map(nodeIds::contains) .collect(Collectors.toSet()); if (inNodes.contains(false)) { return false; } if (inNodes.contains(true)) { return true; } } return false; } // for tests ClusterState state() { return state; } ClusterInfo info() { return info; } private static class ExtendedClusterInfo extends ClusterInfo { private final ClusterInfo delegate; private ExtendedClusterInfo(ImmutableOpenMap<String, Long> extraShardSizes, ClusterInfo info) { super( info.getNodeLeastAvailableDiskUsages(), info.getNodeMostAvailableDiskUsages(), extraShardSizes, ImmutableOpenMap.of(), null, null ); this.delegate = info; } @Override public Long getShardSize(ShardRouting shardRouting) { Long shardSize = super.getShardSize(shardRouting); if (shardSize != null) { return shardSize; } else { return delegate.getShardSize(shardRouting); } } @Override public long getShardSize(ShardRouting shardRouting, long defaultValue) { Long shardSize = super.getShardSize(shardRouting); if (shardSize != null) { return shardSize; } else { return delegate.getShardSize(shardRouting, defaultValue); } } @Override public Optional<Long> getShardDataSetSize(ShardId shardId) { return delegate.getShardDataSetSize(shardId); } @Override public String getDataPath(ShardRouting shardRouting) { return delegate.getDataPath(shardRouting); } @Override public ReservedSpace getReservedSpace(String nodeId, String dataPath) { return delegate.getReservedSpace(nodeId, dataPath); } @Override public void writeTo(StreamOutput out) throws IOException { throw new UnsupportedOperationException(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { throw new UnsupportedOperationException(); } } } public static class ReactiveReason implements AutoscalingDeciderResult.Reason { private final String reason; private final long unassigned; private final long assigned; public ReactiveReason(String reason, long unassigned, long assigned) { this.reason = reason; this.unassigned = unassigned; this.assigned = assigned; } public ReactiveReason(StreamInput in) throws IOException { this.reason = in.readString(); this.unassigned = in.readLong(); this.assigned = in.readLong(); } @Override public String summary() { return reason; } public long unassigned() { return unassigned; } public long assigned() { return assigned; } @Override public String getWriteableName() { return ReactiveStorageDeciderService.NAME; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(reason); out.writeLong(unassigned); out.writeLong(assigned); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("reason", reason); builder.field("unassigned", unassigned); builder.field("assigned", assigned); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReactiveReason that = (ReactiveReason) o; return unassigned == that.unassigned && assigned == that.assigned && reason.equals(that.reason); } @Override public int hashCode() { return Objects.hash(reason, unassigned, assigned); } } }
apache-2.0
idispatch/bde
groups/bal/ball/ball_defaultattributecontainer.t.cpp
59696
// ball_defaultattributecontainer.t.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <ball_defaultattributecontainer.h> #include <bslma_newdeleteallocator.h> #include <bslma_testallocator.h> // for testing only #include <bslma_testallocatorexception.h> // for testing only #include <bsls_types.h> #include <bdls_testutil.h> #include <bsl_cstdlib.h> #include <bsl_iostream.h> #include <bsl_sstream.h> using namespace BloombergLP; using namespace bsl; // automatically added by script //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // The component under test is an in-core value-semantic component in that it // supports all value-semantic operations except 'bdex' streaming. We choose // the default constructor, the 'addAttribute' and the 'removeAttribute' // methods as the primary manipulators, and 'hasValue' as the basic accessor. // The modified 10-step test procedure without the testing for 'bdex' streaming // is then performed. //----------------------------------------------------------------------------- // [ 2] ball::DefaultAttributeContainer(bslma::Allocator *basicAllocator = 0); // [ 7] ball::DefaultAttributeContainer(const ball::DefaultAttributeContainer&, // bslma::Allocator * = 0) // [ 2] ~ball::DefaultAttributeContainer(); // [ 2] int addAttribute(const ball::Attribute& attribute); // [ 2] int removeAttribute(const ball::Attribute& attribute); // [12] void removeAllAttributes(); // [ 9] const ball::DefaultAttributeContainer& operator=(const ball::AS& other) // [ 4] int numAttributes() const; // [ 4] bool hasValue(const ball::Attribute&) const; // [11] const_iterator begin() const; // [11] const_iterator end() const; // [ 5] bsl::ostream& print(bsl::ostream& stream, int lvl, int spl) const; // [ 6] bool operator==(const ball::AS& lhs, const ball::AS& rhs) // [ 6] bool operator!=(const ball::AS& lhs, const ball::AS& rhs) // [ 5] bsl::ostream& operator<<(bsl::ostream&, const ball::AS&) const; //----------------------------------------------------------------------------- // [ 1] BREATHING TEST // [ 3] Obj& gg(Obj *obj, const char *spec); // [ 8] UNUSED // [10] UNUSED // [13] USAGE EXAMPLE // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BDLS_TESTUTIL_ASSERT #define ASSERTV BDLS_TESTUTIL_ASSERTV #define LOOP_ASSERT BDLS_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BDLS_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BDLS_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BDLS_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BDLS_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BDLS_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BDLS_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BDLS_TESTUTIL_LOOP6_ASSERT #define Q BDLS_TESTUTIL_Q // Quote identifier literally. #define P BDLS_TESTUTIL_P // Print identifier and value. #define P_ BDLS_TESTUTIL_P_ // P(X) without '\n'. #define T_ BDLS_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BDLS_TESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- typedef ball::DefaultAttributeContainer Obj; typedef bsls::Types::Int64 Int64; bslma::Allocator *globalAllocator = &bslma::NewDeleteAllocator::singleton(); ball::Attribute A0("", "12345678", globalAllocator); ball::Attribute A1("", 12345678, globalAllocator); ball::Attribute A2("", (Int64)12345678, globalAllocator); ball::Attribute A3("uuid", "12345678", globalAllocator); ball::Attribute A4("uuid", 12345678, globalAllocator); ball::Attribute A5("uuid", (Int64)12345678, globalAllocator); ball::Attribute A6("UUID", "12345678", globalAllocator); ball::Attribute A7("UUID", 12345678, globalAllocator); ball::Attribute A8("UUID", (Int64)12345678, globalAllocator); const char* NAMES[] = { "", // A "A", // B "a", // C "B", // D "b", // E "AA", // F "Aa", // G "AB", // H "Ab", // I "ABCDEFGHIJKLMNOPQRSTUVWXYZ", // J "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // K }; int NUM_NAMES = sizeof NAMES / sizeof *NAMES; //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- bool compareText(bslstl::StringRef lhs, bslstl::StringRef rhs, bsl::ostream& errorStream = bsl::cout) // Return 'true' if the specified 'lhs' has the same value as the // specified' rhs' and 'false' otherwise. Optionally specify a // 'errorStream', on which, if 'lhs' and 'rhs' are not the same', a // description of how the two strings differ will be written. If // 'errorStream' is not supplied, 'stdout' will be used to report an error // description. { for (unsigned int i = 0; i < lhs.length() && i < rhs.length(); ++i) { if (lhs[i] != rhs[i]) { errorStream << "lhs: \"" << lhs << "\"\n" << "rhs: \"" << rhs << "\"\n" << "Strings differ at index (" << i << ") " << "lhs[i] = " << lhs[i] << "(" << (int)lhs[i] << ") " << "rhs[i] = " << rhs[i] << "(" << (int)rhs[i] << ")" << endl; return false; // RETURN } } if (lhs.length() < rhs.length()) { unsigned int i = lhs.length(); errorStream << "lhs: \"" << lhs << "\"\n" << "rhs: \"" << rhs << "\"\n" << "Strings differ at index (" << i << ") " << "lhs[i] = END-OF-STRING " << "rhs[i] = " << rhs[i] << "(" << (int)rhs[i] << ")" << endl; return false; // RETURN } if (lhs.length() > rhs.length()) { unsigned int i = rhs.length(); errorStream << "lhs: \"" << lhs << "\"\n" << "rhs: \"" << rhs << "\"\n" << "Strings differ at index (" << i << ") " << "lhs[i] = " << lhs[i] << "(" << (int)lhs[i] << ") " << "rhs[i] = END-OF-STRING" << endl; return false; // RETURN } return true; } //============================================================================= // GENERATOR FUNCTIONS 'g', 'gg', AND 'ggg' FOR TESTING LISTS //----------------------------------------------------------------------------- // The 'g' family of functions generate a 'ball::DefaultAttributeContainer' // object for testing. They interpret a given 'spec' (from left to right) to // configure the attribute set according to a custom language. // // To simplify these generator functions, an attribute is represented by two // or three characters. The first character must be within ['A' .. 'A' + // NUM_NAMES - 1], indicating an attribute name that can be looked up from the // array NAMES[] defined above. If the second character is an 'i' or 'I', // then the third must be a character within ['0' - '9'], representing // respectively a 32-bit or 64-bit integral value within [0 - 9]. If the // second character is neither 'i' nor 'I' then the second character is used // directly as the string value (with a '\0' character appended). // // LANGUAGE SPECIFICATION: // ----------------------- // // <SPEC> ::= <ATTRIBUTE> * // // <ATTRIBUTE> ::= <NAME> <VALUE> // // <NAME> ::= [ 'A' .. 'A' + NUM_NAMES - 1 ] // // <VALUE> ::= 'i' <INTEGER> // 32-bit // | 'I' <INTEGER> // 64-bit // | <STRING> // // <INTEGER> ::= [ '0' .. '9' ] // // <STRING> ::= any character except 'i' and 'I' // // Spec String Description // ----------- --------------------------------------------------------------- // "" Has no effect; leaves the object unaltered. // "AA" Produces: { A=A } {string value} // "A1" Produces: { A=1 } (string value) // "Ai1" Produces: { A=1 } (32 bit value) // "AI1" Produces: { A=1 } (64 bit value) // "AABB" Produces: { A=A, B=B } //----------------------------------------------------------------------------- static Obj& gg(Obj *obj, const char *spec) { const char *name; while (*spec) { if ('A' > *spec || 'A' + NUM_NAMES <= *spec) { return *obj; // RETURN } name = NAMES[*spec - 'A']; ++spec; switch (*spec) { case 'i': { ++spec; ball::Attribute attr(name, *spec - '0'); obj->addAttribute(attr); } break; case 'I': { ++spec; ball::Attribute attr(name, (Int64)*spec - '0'); obj->addAttribute(attr); } break; default: { string value; value = *spec; ball::Attribute attr(name, value.c_str()); obj->addAttribute(attr); } } ++spec; } return *obj; } //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; int verbose = argc > 2; int veryVerbose = argc > 3; int veryVeryVerbose = argc > 4; bslma::TestAllocator testAllocator(veryVeryVerbose); cout << "TEST " << __FILE__ << " CASE " << test << endl;; switch (test) { case 0: // Zero is always the leading case. case 13: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE // // Concerns: // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Incorporate usage example from header into driver, remove leading // comment characters, and replace 'assert' with 'ASSERT'. Suppress // all 'cout' statements in non-verbose mode, and add streaming to // a buffer to test programmatically the printing examples. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << "\nTesting usage example" << "\n=====================" << endl; ball::DefaultAttributeContainer attributeSet; ball::Attribute a1("uuid", 1111); ball::Attribute a2("sid", "111-1"); ASSERT(1 == attributeSet.addAttribute(a1)); ASSERT(1 == attributeSet.addAttribute(a2)); ball::Attribute a3("uuid", 2222); ball::Attribute a4("sid", "222-2"); ASSERT(1 == attributeSet.addAttribute(a3)); ASSERT(1 == attributeSet.addAttribute(a4)); ball::Attribute a5("uuid", 1111); // same as 'a1' ASSERT(0 == attributeSet.addAttribute(a5)); ball::Attribute a6("UUID", 1111); ASSERT(1 == attributeSet.addAttribute(a6)); ASSERT(true == attributeSet.hasValue(a1)); ASSERT(true == attributeSet.hasValue(a2)); ASSERT(true == attributeSet.hasValue(a3)); ASSERT(true == attributeSet.hasValue(a4)); ASSERT(true == attributeSet.hasValue(a5)); ASSERT(true == attributeSet.hasValue(a6)); attributeSet.removeAttribute(a1); ASSERT(false == attributeSet.hasValue(a1)); ball::DefaultAttributeContainer::const_iterator iter; for (iter = attributeSet.begin(); iter != attributeSet.end(); ++iter ) { if (veryVerbose) { bsl::cout << *iter << bsl::endl; } } } break; case 12: { // -------------------------------------------------------------------- // TESTING 'removeAllAttributes' // The 'removeAllAttributes' should effectively empty the // 'ball::DefaultAttributeContainer' object. // // Plan: // Specify a set S of test vectors. For each element in S, // construct the corresponding 'ball::DefaultAttributeContainer' // object x using the 'gg' function. Copy x into another object y. // After calling 'removeAllAttributes' on x, verify that the length // of x is zero, none of attributes in y can be found in x. Then // reconstruct x using the 'gg' function again, and verify that // x == y. // // Testing: void removeAllAttributes(); // -------------------------------------------------------------------- if (verbose) cout << "\nTesting 'removeAllAttributes" << "\n============================" << endl; static const char* SPECS[] = { "", "AA", "Ai1", "AI1", "AABA", "AABi1", "AABI1", "Ai1BA", "Ai1Bi1", "Ai1BI1", "AI1BA", "AI1Bi1", "AI1BI1", "AABBCC", "AABBCCDD", "AABBCCDDEE", "AABBCCDDEEFF", "AABBCCDDEEFFGG", "AABBCCDDEEFFGGHH", }; const int NUM_SPECS = sizeof SPECS / sizeof *SPECS; for (int i = 0; i < NUM_SPECS; ++i) { for (int j = 0; j < NUM_SPECS; ++j) { if (veryVerbose) { P_(i); P_(j); P_(SPECS[i]); P(SPECS[j]); } Obj mX; const Obj& X = mX; LOOP2_ASSERT(i, j, &mX == &gg(&mX, SPECS[i])); Obj mY; const Obj& Y = mY; LOOP2_ASSERT(i, j, &mY == &gg(&mY, SPECS[j])); mX.removeAllAttributes(); LOOP2_ASSERT(i, j, 0 == X.numAttributes()); for (Obj::const_iterator iter = Y.begin(); iter != Y.end(); ++iter) { LOOP2_ASSERT(i, j, false == X.hasValue(*iter)); } LOOP2_ASSERT(i, j, &mX == &gg(&mX, SPECS[j])); LOOP2_ASSERT(i, j, X == Y); } } } break; case 11: { // -------------------------------------------------------------------- // TESTING 'begin()' and 'end' // This will test the 'begin()' and 'end()' methods. // // Concerns: // The 'begin() and 'end()' methods should return a range where each // attribute in the attribute set appears exactly once. // // Plan: // Construct an array consisting of 'ball::Attribute' objects having // distinct values. For each n in [0 .. N] where N is the maximum // number of attributes tested, create an empty // 'ball::DefaultAttributeContainer' object and add the first n // attributes to the set. Verify that every added attributes appear // in the set exactly once. // // Testing: // const_iterator begin() const; // const_iterator end() const; // int numAttributes() const; // -------------------------------------------------------------------- if (verbose) cout << "\nTesting 'begin()' and 'end()'" << "\n=============================" << endl; const ball::Attribute* ATTRS[] = { &A0, &A1, &A2, &A3, &A4, &A5, &A6, &A7, &A8 }; const int NUM_ATTRS = sizeof ATTRS / sizeof *ATTRS; int isPresentFlags[NUM_ATTRS]; for (int i = 0; i < NUM_ATTRS; ++i) { Obj mX; const Obj& X = mX; int j, length; for (j = 0; j < i; ++j) { LOOP2_ASSERT(i, j, 1 == mX.addAttribute(*ATTRS[j])); LOOP2_ASSERT(i, j, X.hasValue(*ATTRS[j])); isPresentFlags[j] = 0; } LOOP_ASSERT(i, j == X.numAttributes()); length = 0; for (Obj::const_iterator iter = X.begin(); iter != X.end(); ++iter, ++length) { for (j = 0; j < i; ++j) { if (*iter == *ATTRS[j]) { ++isPresentFlags[j]; } } } LOOP_ASSERT(i, length == X.numAttributes()); for (j = 0; j < i; ++j) { LOOP2_ASSERT(i, j, 1 == isPresentFlags[j]); } } } break; case 10: { // -------------------------------------------------------------------- // TESTING 'bdex' STREAMING FUNCTIONALITY: // Void for 'ball::AttributeSET'. // -------------------------------------------------------------------- } break; case 9: { // -------------------------------------------------------------------- // TESTING ASSIGNMENT OPERATOR: // Any value must be assignable to an object having any initial value // without affecting the rhs operand value. Also, any object must be // assignable to itself. // // Plan: // Specify a set S of (unique) objects with substantial and varied // differences in value. Construct and initialize all combinations // (u, v) in the cross product S x S, copy construct a control w from // v, assign v to u, and assert that w == u and w == v. Then test // aliasing by copy constructing a control w from each u in S, // assigning u to itself, and verifying that w == u. // // Testing: // const ball::DefaultAttributeContainer& operator=( // const ball::AS& other) // -------------------------------------------------------------------- if (verbose) cout << "\nTesting Assignment Operator" << "\n==========================" << endl; static const struct { int d_line; // source line number const char *d_spec; // input 'spec' string for 'gg' } DATA[] = { // line spec // ---- ---- { L_, "", }, { L_, "AA", }, { L_, "Ai1", }, { L_, "AI1", }, { L_, "AABA", }, { L_, "AABi1", }, { L_, "AABI1", }, { L_, "Ai1BA", }, { L_, "Ai1Bi1", }, { L_, "Ai1BI1", }, { L_, "AI1BA", }, { L_, "AI1Bi1", }, { L_, "AI1BI1", }, { L_, "AABBCC", }, { L_, "AABBCCDD", }, { L_, "AABBCCDDEE", }, { L_, "AABBCCDDEEFF", }, { L_, "AABBCCDDEEFFGG", }, { L_, "AABBCCDDEEFFGGHH", }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE1 = DATA[i].d_line; for (int j = 0; j < NUM_DATA; ++j) { const int LINE2 = DATA[j].d_line; if (veryVerbose) { P_(LINE1); P_(DATA[i].d_spec); P_(LINE2); P(DATA[j].d_spec); } Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE1, &mX == &gg(&mX, DATA[i].d_spec)); Obj mY; const Obj& Y = mY; LOOP_ASSERT(LINE2, &mY == &gg(&mY, DATA[j].d_spec)); Obj mW(Y); const Obj& W = mW; mX = Y; LOOP2_ASSERT(LINE1, LINE2, Y == W); LOOP2_ASSERT(LINE1, LINE2, W == Y); LOOP2_ASSERT(LINE1, LINE2, X == W); LOOP2_ASSERT(LINE1, LINE2, W == X); } } if (verbose) cout << "\nTesting assignment u = u (Aliasing)." << endl; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; if (veryVerbose) { P_(LINE); P_(DATA[i].d_spec); } Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE, &mX == &gg(&mX, DATA[i].d_spec)); Obj mW(X); const Obj& W = mW; mX = X; LOOP_ASSERT(LINE, X == W); LOOP_ASSERT(LINE, W == X); } } break; case 8: { // -------------------------------------------------------------------- // TESTING SECONDARY TEST APPARATUS: // Void for 'ball::DefaultAttributeContainer'. // -------------------------------------------------------------------- } break; case 7: { // -------------------------------------------------------------------- // TESTING COPY CONSTRUCTOR: // Any value must be able to be copy constructed without affecting // its argument. // // Plan: // Specify a set S whose elements have substantial and varied // differences in value. For each element in S, construct and // initialize identically valued objects w and x using 'gg'. Then // copy construct an object y from x, and use the equality operator // to assert that both x and y have the same value as w. // // Testing: // ball::DefaultAttributeContainer( // const ball::DefaultAttributeContainer&, // bslma::Allocator * = 0) // -------------------------------------------------------------------- if (verbose) cout << "\nTesting Copy Constructor" << "\n========================" << endl; static const struct { int d_line; // source line number const char *d_spec; // input 'spec' string for 'gg' } DATA[] = { // line spec // ---- ---- { L_, "", }, { L_, "AA", }, { L_, "Ai1", }, { L_, "AI1", }, { L_, "AABA", }, { L_, "AABi1", }, { L_, "AABI1", }, { L_, "Ai1BA", }, { L_, "Ai1Bi1", }, { L_, "Ai1BI1", }, { L_, "AI1BA", }, { L_, "AI1Bi1", }, { L_, "AI1BI1", }, { L_, "AABBCC", }, { L_, "AABBCCDD", }, { L_, "AABBCCDDEE", }, { L_, "AABBCCDDEEFF", }, { L_, "AABBCCDDEEFFGG", }, { L_, "AABBCCDDEEFFGGHH", }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; if (veryVerbose) { P_(LINE); P(DATA[i].d_spec); } Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE, &mX == &gg(&mX, DATA[i].d_spec)); Obj mW; const Obj& W = mW; LOOP_ASSERT(LINE, &mW == &gg(&mW, DATA[i].d_spec)); // construct y without an allocator { Obj mY(X); const Obj& Y = mY; LOOP_ASSERT(LINE, Y == W); LOOP_ASSERT(LINE, W == Y); LOOP_ASSERT(LINE, X == W); LOOP_ASSERT(LINE, W == X); } // construct y with an allocator but no exception { bslma::TestAllocator testAllocatorY(veryVeryVerbose); Obj mY(X, &testAllocatorY); const Obj& Y = mY; LOOP_ASSERT(LINE, Y == W); LOOP_ASSERT(LINE, W == Y); LOOP_ASSERT(LINE, X == W); LOOP_ASSERT(LINE, W == X); } // construct y with an allocator and exceptions { bslma::TestAllocator testAllocatorY(veryVeryVerbose); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) { Obj mY(X, &testAllocatorY); const Obj& Y = mY; LOOP_ASSERT(LINE, Y == W); LOOP_ASSERT(LINE, W == Y); LOOP_ASSERT(LINE, X == W); LOOP_ASSERT(LINE, W == X); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END } } } break; case 6: { // -------------------------------------------------------------------- // TESTING EQUALITY OPERATORS: // Any subtle variation in value must be detected by the equality // operators. // // Plan: // First, specify a set S of unique object values that may have // various minor or subtle differences. Verify the correctness of // 'operator==' and 'operator!=' using all elements (u, v) of the // cross product S X S. // // Next, specify another set T where each element is a pair of // different specifications having the same value (the same // attributes were added in different orders). For each element (u, // v) in T, verify that 'operator==' and 'operator!=' return the // correct value. // Testing: // bool operator==(const ball::AS& lhs, const ball::AS& rhs) // bool operator!=(const ball::AS& lhs, const ball::AS& rhs) // -------------------------------------------------------------------- static const struct { int d_line; // source line number const char *d_spec; // input 'spec' string for 'gg' } DATA[] = { // line spec // ---- ---- { L_, "" }, { L_, "AA" }, { L_, "Ai1" }, { L_, "AI1" }, { L_, "BA" }, { L_, "Bi1" }, { L_, "BI1" }, { L_, "BB" }, { L_, "BC" }, { L_, "AABA" }, { L_, "AAAB" }, { L_, "Ai1BA" }, { L_, "Ai1Bi1" }, { L_, "Ai1BI1" }, { L_, "AI1Bi1" }, { L_, "AI2Bi1" }, { L_, "BBAi1" }, { L_, "Ai1BI2" }, { L_, "AABBCC" }, { L_, "AABBCCDD" }, { L_, "AABBCCDDEE" }, { L_, "AABBCCDDEEFF" }, { L_, "AABBCCDDEEFFGG" }, { L_, "AABBCCDDEEFFGGHH" }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; if (verbose) cout << "\nTesting Equality Operators" << "\n==========================" << endl; if (verbose) cout << "\nCompare u against v for each (u, v) in S X S." << endl; for (int i = 0; i < NUM_DATA; ++i) { const int LINE1 = DATA[i].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE1, &mX == &gg(&mX, DATA[i].d_spec)); for (int j = 0; j < NUM_DATA; ++j) { const int LINE2 = DATA[j].d_line; if (veryVerbose) { P_(LINE1); P_(DATA[i].d_spec); P_(LINE2); P(DATA[j].d_spec); } Obj mY; const Obj& Y = mY; LOOP_ASSERT(LINE1, &mY == &gg(&mY, DATA[j].d_spec)); LOOP2_ASSERT(LINE1, LINE2, (i==j) == (X == Y)); LOOP2_ASSERT(LINE1, LINE2, (i!=j) == (X != Y)); } } if (verbose) cout << "\nCompare w~u against v for each (w, u, v) in S X S X S." << endl; for (int i = 0; i < NUM_DATA; ++i) { for (int j = 0; j < NUM_DATA; ++j) { for (int k = 0; k < NUM_DATA; ++k) { const int LINE1 = DATA[i].d_line; const int LINE2 = DATA[j].d_line; const int LINE3 = DATA[k].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE1, &mX == &gg(&mX, DATA[i].d_spec)); mX.removeAllAttributes(); LOOP2_ASSERT(LINE1, LINE2, &mX == &gg(&mX, DATA[j].d_spec)); Obj mY; const Obj& Y = mY; LOOP_ASSERT(LINE3, &mY == &gg(&mY, DATA[k].d_spec)); if (veryVerbose) { P_(LINE1); P_(DATA[i].d_spec); P_(LINE2); P_(DATA[j].d_spec); P_(LINE3); P(DATA[k].d_spec); } LOOP3_ASSERT(LINE1, LINE2, LINE3, (j == k) == (X == Y)); LOOP3_ASSERT(LINE1, LINE2, LINE3, (j != k) == (X != Y)); } } } static const struct { int d_line; // source line number const char *d_spec1; // input 'spec' string for 'gg' const char *d_spec2; // input 'spec' string for 'gg' } TDATA[] = { // line spec1 spec2 // ---- ----- ----- { L_, "", "", }, { L_, "AABA", "BAAA", }, { L_, "AABA", "BAAA", }, { L_, "Ai1BA", "BAAi1", }, { L_, "Ai1BI1", "BI1Ai1", }, { L_, "Ai1BI1", "BI1Ai1", }, { L_, "AABBCC", "AACCBB", }, { L_, "AABBCC", "BBAACC", }, { L_, "AABBCC", "BBCCAA", }, { L_, "AABBCC", "CCAABB", }, { L_, "AABBCC", "CCBBAA", }, { L_, "AABBCCDD", "DDCCBBAA", }, { L_, "AABBCCDDEE", "EEDDCCBBAA", }, { L_, "AABBCCDDEEFF", "FFEEDDCCBBAA", }, { L_, "AABBCCDDEEFFGG", "GGFFEEDDCCBBAA", }, { L_, "AABBCCDDEEFFGGHH", "HHGGFFEEDDCCBBAA", }, }; const int NUM_TDATA = sizeof TDATA / sizeof *TDATA; if (verbose) cout << "\nCompare u against u for each u in T." << endl; for (int i = 0; i < NUM_TDATA; ++i) { const int LINE = TDATA[i].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE, &mX == &gg(&mX, TDATA[i].d_spec1)); Obj mY; const Obj& Y = mY; LOOP_ASSERT(LINE, &mY == &gg(&mY, TDATA[i].d_spec2)); if (veryVerbose) { P_(LINE); P_(TDATA[i].d_spec1); P(TDATA[i].d_spec2); } LOOP_ASSERT(LINE, 1 == (X == Y)); LOOP_ASSERT(LINE, 0 == (X != Y)); } if (verbose) cout << "\nCompare w~u against u in each (w, u) in S X S." << endl; for (int i = 0; i < NUM_TDATA; ++i) { for (int j = 0; j < NUM_TDATA; ++j) { const int LINE1 = TDATA[i].d_line; const int LINE2 = TDATA[j].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE1, &mX == &gg(&mX, TDATA[i].d_spec1)); mX.removeAllAttributes(); LOOP2_ASSERT(LINE1, LINE2, &mX == &gg(&mX, TDATA[j].d_spec1)); Obj mY; const Obj& Y = mY; LOOP_ASSERT(LINE2, &mY == &gg(&mY, TDATA[j].d_spec2)); if (veryVerbose) { P_(LINE1); P_(TDATA[i].d_spec1); P_(LINE2); P_(TDATA[j].d_spec1); P(TDATA[j].d_spec2); } LOOP2_ASSERT(LINE1, LINE2, 1 == (X == Y)); LOOP2_ASSERT(LINE1, LINE2, 0 == (X != Y)); } } } break; case 5: { // -------------------------------------------------------------------- // TESTING 'operator<<' AND 'print': // The output operator and 'print' method should print out the value // of objects in the expected format. // // Plan: // For each of a small representative set of object values, use // 'ostrstream' to write that object's value to a character buffer // and then compare the contents of that buffer with the expected // output format. // // Testing: // bsl::ostream& operator<<(bsl::ostream&, const ball::AS&) const; // bsl::ostream& print(bsl::ostream& stream, int lvl, int spl) const; // -------------------------------------------------------------------- if (verbose) cout << endl << "Testing 'operator<<' and 'print'" << endl << "================================" << endl; if (verbose) cout << "\nTesting 'operator<<' (ostream)." << endl; static const struct { int d_line; // line number const char *d_spec; // spec const char *d_output; // expected output format } DATA[] = { // line spec expected output // ---- ---- --------------- { L_, "", "[ ]" }, { L_, "AA", "[ [ \"\" = A ] ]" }, { L_, "Ai1", "[ [ \"\" = 1 ] ]" }, { L_, "AI1", "[ [ \"\" = 1 ] ]" }, { L_, "BB", "[ [ \"A\" = B ] ]" }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int i = 0; i < NUM_DATA; ++i) { const int LINE = DATA[i].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE, &mX == &gg(&mX, DATA[i].d_spec)); ostringstream os; os << X; LOOP_ASSERT(LINE, compareText(os.str(), DATA[i].d_output)); if (veryVerbose) { P_(LINE); P_(DATA[i].d_spec); P_(DATA[i].d_output); P(os.str()); } } if (verbose) cout << "\nTesting 'print'." << endl; static const struct { int d_line; // line number const char *d_spec; // spec for gg int d_level; // tab level int d_spacesPerLevel; // spaces per level const char *d_output; // expected output format } PDATA[] = { // line spec level space expected // ---- ---- ----- ----- ----------------------- { L_, "BA", 1, 2, " [\n" " [ \"A\" = A ]\n" " ]\n" }, }; const int NUM_PDATA = sizeof PDATA / sizeof *PDATA; for (int i = 0; i < NUM_PDATA; ++i) { int LINE = PDATA[i].d_line; Obj mX; const Obj& X = mX; LOOP_ASSERT(LINE, &mX == &gg(&mX, PDATA[i].d_spec)); ostringstream os; X.print(os, PDATA[i].d_level, PDATA[i].d_spacesPerLevel); if (veryVerbose) { P_(LINE); P_(PDATA[i].d_spec); P(PDATA[i].d_output); P(os.str()); } LOOP_ASSERT(LINE, compareText(os.str(), PDATA[i].d_output)); } } break; case 4: { // -------------------------------------------------------------------- // TESTING BASIC ACCESSORS // Every attribute added must be verified by 'hasValue'. // // Plan: // Mechanically generate a series of specifications whose contain // string attributes with names 'A' .. 'A' + NUM_NAMES and with // values 'A' .. 'J', and integral attributes with name 'a' .. 'j' // and with values 0 .. 9. For each specification, create an // attribute set from the specification, and verify that the // attributes with the specified names having the specified values // exist. // // Testing (indirectly): // bool hasValue(const ball::Attribute&) const; // int numAttributes() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "Testing Basic Accessors" << endl; for (int n = 0; n < NUM_NAMES; ++n) { bsl::string spec; for (int v = 0; v < n; ++v) { spec += (char)n + 'A'; // add a string attribute // don't use 'I' as the string attribute value spec += v >= 'I' - 'A'? (char)v + 'B' : (char)v + 'A' ; spec += (char)n + 'A'; // add an int32 attribute spec += 'i'; spec += (char)v + '0'; spec += (char)n + 'A'; // add an int64 attribute spec += 'I'; spec += (char)v + '0'; } Obj mX; const Obj& X = mX; LOOP_ASSERT(n, &mX == &gg(&mX, spec.c_str())); LOOP_ASSERT(n, X.numAttributes() == 3 * n); if (veryVerbose) { P_(n); P(spec); } for (int v = 0; v <= '9' - '0'; ++v) { bsl::string sValue; sValue = v >= 'I' - 'A'? (char)v + 'B' : (char)v + 'A'; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], sValue.c_str()))); int int32Value = v; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], int32Value))); Int64 int64Value = v; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], int64Value))); } } } break; case 3: { // -------------------------------------------------------------------- // TESTING GENERATOR FUNCTIONS 'GG' // The 'gg' function must create objects having the expected values. // // Plan: // Mechanically generate a series of specifications whose contain // string attributes with names 'A' .. 'A' + NUM_NAMES and with // values 'A' .. 'J', and integral attributes with name 'a' .. 'j' // and with values 0 .. 9. For each specification, create an // attribute set from the specification, and verify that the // attributes with the specified names having the specified values // exist. // // Testing: // Obj& gg(Obj *address, const char *spec); // -------------------------------------------------------------------- if (verbose) cout << endl << "Testing 'gg' generator function" << endl << "===============================" << endl; for (int n = 0; n < NUM_NAMES; ++n) { bsl::string spec; for (int v = 0; v < n; ++v) { spec += (char)n + 'A'; // add a string attribute // don't use 'I' as the string attribute value spec += v >= 'I' - 'A'? (char)v + 'B' : (char)v + 'A' ; spec += (char)n + 'A'; // add an int32 attribute spec += 'i'; spec += (char)v + '0'; spec += (char)n + 'A'; // add an int64 attribute spec += 'I'; spec += (char)v + '0'; } Obj mX; const Obj& X = mX; LOOP_ASSERT(n, &mX == &gg(&mX, spec.c_str())); LOOP_ASSERT(n, X.numAttributes() == 3 * n); if (veryVerbose) { P_(n); P(spec); } for (int v = 0; v <= '9' - '0'; ++v) { bsl::string sValue; sValue = v >= 'I' - 'A'? (char)v + 'B' : (char)v + 'A'; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], sValue.c_str()))); int int32Value = v; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], int32Value))); Int64 int64Value = v; LOOP2_ASSERT(n, v, (v < n) == X.hasValue( ball::Attribute(NAMES[n], int64Value))); } } } break; case 2: { // -------------------------------------------------------------------- // TESTING PRIMARY MANIPULATORS (BOOTSTRAP): // Setter functions should correctly pass the specified value to the // object. // // Plan: // For a sequence of independent test values, use the constructor to // create an object and use the primary manipulators to set its // value. For each value that is valid, verify, using the basic // accessors, that the value has been assigned to the object; // otherwise verify that the original value of the object is // retained. // // Testing: // ball::DefaultAttributeContainer( // bslma::Allocator *basicAllocator = 0); // int addAttribute(const ball::Attribute& attribute); // int removeAttribute(const ball::Attribute& attribute); // ~ball::DefaultAttributeContainer(); // -------------------------------------------------------------------- if (verbose) cout << "\nTesting Primary Manipulator" << "\n===========================" << endl; if (verbose) cout << "\nTesting default ctor (thoroughly)." << endl; if (verbose) cout << "\tWithout passing in an allocator." << endl; { const Obj X((bslma::Allocator *)0); if (veryVerbose) { cout << "\t\t"; P(X); } } if (verbose) cout << "\tPassing in an allocator." << endl; if (verbose) cout << "\t\tWith no exceptions." << endl; { const Obj X(&testAllocator); if (veryVerbose) { cout << "\t\t"; P(X); } } if (verbose) cout << "\t\tWith exceptions." << endl; { BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) { if (veryVerbose) cout << "\tTesting Exceptions In Default Ctor" << endl; const Obj X(&testAllocator); if (veryVerbose) { cout << "\t\t"; P(X); } } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END } if (verbose) cout << "\nTesting primary manipulator." << endl; if (verbose) cout << "\tWithout passing in an allocator." << endl; { Obj mX; const Obj& X = mX; Obj mY; const Obj& Y = mY; ASSERT(1 == mY.addAttribute(A1)); Obj mZ; const Obj& Z = mZ; ASSERT(1 == mZ.addAttribute(A2)); ASSERT(1 == mZ.addAttribute(A3)); if (veryVeryVerbose) { P(mX); P(mY); P(mZ); } ASSERT(0 == (X == Y)); ASSERT(0 == (X == Z)); ASSERT(0 == (Y == Z)); ASSERT(0 == X.numAttributes()); ASSERT(1 == Y.numAttributes()); ASSERT(2 == Z.numAttributes()); ASSERT(Y.hasValue(A1)); ASSERT(Z.hasValue(A2)); ASSERT(Z.hasValue(A3)); if (veryVerbose) cout << "\tSetting mX with mY's initializer." << endl; ASSERT(1 == mX.addAttribute(A1)); ASSERT(1 == X.numAttributes()); ASSERT(X.hasValue(A1)); ASSERT(X == Y); if (veryVerbose) cout << "\tSetting mX with mZ's initializer." << endl; ASSERT(1 == mX.removeAttribute(A1)); ASSERT(false == X.hasValue(A1)); ASSERT(1 == mX.addAttribute(A2)); ASSERT(1 == mX.addAttribute(A3)); ASSERT(2 == X.numAttributes()); ASSERT(X.hasValue(A2)); ASSERT(X.hasValue(A3)); ASSERT(X == Z); } if (verbose) cout << "\tWith an allocator." << endl; if (verbose) cout << "\t\tWithout exceptions." << endl; { bslma::TestAllocator testAllocatorX(veryVeryVerbose); bslma::TestAllocator testAllocatorY(veryVeryVerbose); bslma::TestAllocator testAllocatorZ(veryVeryVerbose); Obj mX(&testAllocatorX); const Obj& X = mX; Obj mY(&testAllocatorY); const Obj& Y = mY; ASSERT(1 == mY.addAttribute(A1)); Obj mZ(&testAllocatorZ); const Obj& Z = mZ; ASSERT(1 == mZ.addAttribute(A2)); ASSERT(1 == mZ.addAttribute(A3)); if (veryVeryVerbose) { P(mX); P(mY); P(mZ); } ASSERT(0 == (X == Y)); ASSERT(0 == (X == Z)); ASSERT(0 == (Y == Z)); ASSERT(0 == X.numAttributes()); ASSERT(1 == Y.numAttributes()); ASSERT(2 == Z.numAttributes()); ASSERT(Y.hasValue(A1)); ASSERT(Z.hasValue(A2)); ASSERT(Z.hasValue(A3)); if (veryVerbose) cout << "\tSetting mX with mY's initializer." << endl; ASSERT(1 == mX.addAttribute(A1)); ASSERT(1 == X.numAttributes()); ASSERT(X.hasValue(A1)); ASSERT(X == Y); if (veryVerbose) cout << "\tSetting mX with mZ's initializer." << endl; ASSERT(1 == mX.removeAttribute(A1)); ASSERT(false == X.hasValue(A1)); ASSERT(1 == mX.addAttribute(A2)); ASSERT(1 == mX.addAttribute(A3)); ASSERT(2 == X.numAttributes()); ASSERT(X.hasValue(A2)); ASSERT(X.hasValue(A3)); ASSERT(X == Z); } if (verbose) cout << "\t\tWith exceptions." << endl; { bslma::TestAllocator testAllocatorX(veryVeryVerbose); bslma::TestAllocator testAllocatorY(veryVeryVerbose); bslma::TestAllocator testAllocatorZ(veryVeryVerbose); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator) { if (veryVerbose) cout << "\tTesting Exceptions In Primary Manipulator" << endl; Obj mX(&testAllocatorX); const Obj& X = mX; Obj mY(&testAllocatorY); const Obj& Y = mY; ASSERT(1 == mY.addAttribute(A1)); Obj mZ(&testAllocatorZ); const Obj& Z = mZ; ASSERT(1 == mZ.addAttribute(A2)); ASSERT(1 == mZ.addAttribute(A3)); if (veryVeryVerbose) { P(mX); P(mY); P(mZ); } ASSERT(0 == (X == Y)); ASSERT(0 == (X == Z)); ASSERT(0 == (Y == Z)); ASSERT(0 == X.numAttributes()); ASSERT(1 == Y.numAttributes()); ASSERT(2 == Z.numAttributes()); ASSERT(Y.hasValue(A1)); ASSERT(Z.hasValue(A2)); ASSERT(Z.hasValue(A3)); if (veryVerbose) cout << "\tSetting mX with mY's initializer." << endl; ASSERT(1 == mX.addAttribute(A1)); ASSERT(1 == X.numAttributes()); ASSERT(X.hasValue(A1)); ASSERT(X == Y); if (veryVerbose) cout << "\tSetting mX with mZ's initializer." << endl; ASSERT(1 == mX.removeAttribute(A1)); ASSERT(false == X.hasValue(A1)); ASSERT(1 == mX.addAttribute(A2)); ASSERT(1 == mX.addAttribute(A3)); ASSERT(2 == X.numAttributes()); ASSERT(X.hasValue(A2)); ASSERT(X.hasValue(A3)); ASSERT(X == Z); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END } } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST: // Exercise a broad cross-section of value-semantic functionality // before beginning testing in earnest. Probe that functionality // systematically and incrementally to discover basic errors in // isolation. // // Plan: // Create four test objects by using the initializing and copy // constructors. Exercise the basic value-semantic methods and the // equality operators using these test objects. Invoke the primary // manipulator [3, 6], copy constructor [2, 8], and assignment // operator without [9, 10] and with [11, 12] aliasing. Use the // direct accessors to verify the expected results. Display object // values frequently in verbose mode. Note that 'VA', 'VB', and // 'VC' denote unique, but otherwise arbitrary, object values, while // '0' denotes the default object value. // // 1. Create an default object x1. { x1:0 } // 2. Create an object x2 (copy from x1). { x1:0 x2:0 } // 3. Set x1 to VA. { x1:VA x2:0 } // 4. Set x2 to VA. { x1:VA x2:VA } // 5. Set x2 to VB. { x1:VA x2:VB } // 6. Set x1 to 0. { x1:0 x2:VB } // 7. Create an object x3 (with value VC). { x1:0 x2:VB x3:VC } // 8. Create an object x4 (copy from x1). { x1:0 x2:VB x3:VC x4:0 } // 9. Assign x2 = x1. { x1:0 x2:0 x3:VC x4:0 } // 10. Assign x2 = x3. { x1:0 x2:VC x3:VC x4:0 } // 11. Assign x1 = x1 (aliasing). { x1:0 x2:VC x3:VC x4:0 } // 12. Assign x2 = x2 (aliasing). { x1:0 x2:VC x3:VC x4:0 } // // Testing: // This Test Case exercises basic value-semantic functionality. // -------------------------------------------------------------------- if (verbose) cout << "\nBREATHING TEST" << "\n==============" << endl; if (verbose) cout << "\n 1. Create a default object x1." << endl; Obj mX1; const Obj& X1 = mX1; ASSERT(0 == X1.numAttributes()); if (verbose) cout << "\n 2. Create an object x2 (copy from x1)." << endl; Obj mX2(X1); const Obj& X2 = mX2; ASSERT(0 == X2.numAttributes()); ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); if (verbose) cout << "\n 3. Set x1 to VA." << endl; mX1.addAttribute(A1); mX1.addAttribute(A2); ASSERT(2 == X1.numAttributes()); ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); if (verbose) cout << "\n 4. Set x2 to VA." << endl; mX2.addAttribute(A1); mX2.addAttribute(A2); ASSERT(2 == X2.numAttributes()); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(1 == (X1 == X2)); ASSERT(0 == (X1 != X2)); if (verbose) cout << "\n 5. Set x2 to VB." << endl; mX2.removeAllAttributes(); mX2.addAttribute(A3); mX2.addAttribute(A4); ASSERT(2 == X2.numAttributes()); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); if (verbose) cout << "\n 6. Set x1 to 0." << endl; mX1.removeAllAttributes(); ASSERT(0 == X1.numAttributes()); ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); if (verbose) cout << "\n 7. Create an object x3 (with value VC)." << endl; Obj mX3; const Obj& X3 = mX3; mX3.addAttribute(A5); ASSERT(1 == X3.numAttributes()); ASSERT(1 == (X3 == X3)); ASSERT(0 == (X3 != X3)); ASSERT(0 == (X3 == X1)); ASSERT(1 == (X3 != X1)); ASSERT(0 == (X3 == X2)); ASSERT(1 == (X3 != X2)); if (verbose) cout << "\n 8. Create an object x4 (copy from x1)." << endl; Obj mX4(X1); const Obj& X4 = mX4; ASSERT(0 == X4.numAttributes()); ASSERT(1 == (X4 == X1)); ASSERT(0 == (X4 != X1)); ASSERT(0 == (X4 == X2)); ASSERT(1 == (X4 != X2)); ASSERT(0 == (X4 == X3)); ASSERT(1 == (X4 != X3)); ASSERT(1 == (X4 == X4)); ASSERT(0 == (X4 != X4)); if (verbose) cout << "\n 9. Assign x2 = x1." << endl; mX2 = X1; ASSERT(0 == X2.numAttributes()); ASSERT(1 == (X2 == X1)); ASSERT(0 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(0 == (X2 == X3)); ASSERT(1 == (X2 != X3)); ASSERT(1 == (X2 == X4)); ASSERT(0 == (X2 != X4)); if (verbose) cout << "\n 10. Assign x2 = x3." << endl; mX2 = X3; ASSERT(1 == X2.numAttributes()); ASSERT(0 == (X2 == X1)); ASSERT(1 == (X2 != X1)); ASSERT(1 == (X2 == X2)); ASSERT(0 == (X2 != X2)); ASSERT(1 == (X2 == X3)); ASSERT(0 == (X2 != X3)); ASSERT(0 == (X2 == X4)); ASSERT(1 == (X2 != X4)); if (verbose) cout << "\n 11. Assign x1 = x1 (aliasing)." << endl; mX1 = X1; ASSERT(0 == X1.numAttributes()); ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); ASSERT(0 == (X1 == X3)); ASSERT(1 == (X1 != X3)); ASSERT(1 == (X1 == X4)); ASSERT(0 == (X1 != X4)); if (verbose) cout << "\n 12. Assign x2 = x2 (aliasing)." << endl; mX2 = X2; ASSERT(1 == X2.numAttributes()); ASSERT(1 == (X1 == X1)); ASSERT(0 == (X1 != X1)); ASSERT(0 == (X1 == X2)); ASSERT(1 == (X1 != X2)); ASSERT(0 == (X1 == X3)); ASSERT(1 == (X1 != X3)); ASSERT(1 == (X1 == X4)); ASSERT(0 == (X1 != X4)); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } break; } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
apache-2.0
Derzhevitskiy/spring-petclinic-master
src/main/java/org/mybatis/jpetstore/domain/CartItem.java
1767
/** * Copyright 2010-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; /** * @author Eduardo Macarron * */ public class CartItem implements Serializable { private static final long serialVersionUID = 6620528781626504362L; private Item item; private int quantity; private boolean inStock; private BigDecimal total; public boolean isInStock() { return inStock; } public void setInStock(boolean inStock) { this.inStock = inStock; } public BigDecimal getTotal() { return total; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; calculateTotal(); } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; calculateTotal(); } public void incrementQuantity() { quantity++; calculateTotal(); } private void calculateTotal() { if (item != null && item.getListPrice() != null) { total = item.getListPrice().multiply(new BigDecimal(quantity)); } else { total = null; } } }
apache-2.0
objectiser/camel
components/camel-aws-swf/src/test/java/org/apache/camel/component/aws/swf/integration/CamelSWFEndToEndTest.java
3585
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws.swf.integration; import org.apache.camel.EndpointInject; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.aws.swf.SWFConstants; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Ignore; import org.junit.Test; import static org.apache.camel.component.mock.MockEndpoint.assertIsSatisfied; @Ignore("Must be manually tested. Provide your own accessKey and secretKey and also create a SWF domain in advance") public class CamelSWFEndToEndTest extends CamelTestSupport { protected String options = "accessKey=XXX" + "&secretKey=YYY" + "&domainName=ZZZ" + "&activityList=swf-alist" + "&workflowList=swf-wlist" + "&clientConfiguration.endpoint=swf.eu-west-1.amazonaws.com" + "&version=1.0"; @EndpointInject("mock:starter") private MockEndpoint starter; @EndpointInject("mock:decider") private MockEndpoint decider; @EndpointInject("mock:worker") private MockEndpoint worker; @Test public void consumerReceivedPreAndPostEntryCreatedEventNotifications() throws Exception { starter.expectedMessageCount(1); decider.expectedMinimumMessageCount(1); worker.expectedMessageCount(2); template.requestBody("direct:start", "Hello world!"); assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from("aws-swf://activity?" + options + "&eventName=processActivities") .log("FOUND ACTIVITY TASK ${body}") .setBody(constant("1")) .to("mock:worker"); from("aws-swf://workflow?" + options + "&eventName=processWorkflows") .log("FOUND WORKFLOW TASK ${body}") .filter(header(SWFConstants.ACTION).isEqualTo(SWFConstants.EXECUTE_ACTION)) .to("aws-swf://activity?" + options + "&eventName=processActivities") .setBody(constant("Message two")) .to("aws-swf://activity?" + options + "&eventName=processActivities") .log("SENT ACTIVITY TASK ${body}") .to("mock:decider"); from("direct:start") .to("aws-swf://workflow?" + options + "&eventName=processWorkflows") .log("SENT WORKFLOW TASK ${body}") .to("mock:starter"); } }; } }
apache-2.0
ilantukh/ignite
modules/web-console/frontend/app/modules/dialog/dialog.module.js
1283
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import angular from 'angular'; import igniteDialog from './dialog.directive'; import igniteDialogTitle from './dialog-title.directive'; import igniteDialogContent from './dialog-content.directive'; import IgniteDialog from './dialog.factory'; angular .module('ignite-console.dialog', [ ]) .factory('IgniteDialog', IgniteDialog) .directive('igniteDialog', igniteDialog) .directive('igniteDialogTitle', igniteDialogTitle) .directive('igniteDialogContent', igniteDialogContent);
apache-2.0
malakasilva/carbon-identity
components/identity/org.wso2.carbon.identity.application.authenticator.facebook/src/main/java/org/wso2/carbon/identity/application/authenticator/facebook/FacebookAuthenticatorConstants.java
1678
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.application.authenticator.facebook; public class FacebookAuthenticatorConstants { public static final String AUTHENTICATOR_NAME = "FacebookAuthenticator"; // TODO : Change login type public static final String FACEBOOK_LOGIN_TYPE = "facebook"; public static final String LOGIN_TYPE = "loginType"; public static final String OAUTH2_GRANT_TYPE_CODE = "code"; public static final String OAUTH2_PARAM_STATE = "state"; public static final String USERNAME = "id"; public static final String FB_AUTHZ_URL = "http://www.facebook.com/dialog/oauth"; public static final String FB_TOKEN_URL = "https://graph.facebook.com/oauth/access_token"; public static final String FB_USER_INFO_URL = "https://graph.facebook.com/me"; public static final String SCOPE = "email"; public static final String CLIENT_ID = "ClientId"; public static final String CLIENT_SECRET = "ClientSecret"; private FacebookAuthenticatorConstants() { } }
apache-2.0
hisamith/app-cloud
modules/jaggeryapps/appmgt/src/site/themes/default/js/CodeMirror-5.7.0/addon/search/searchonly.js
9107
/* global CodeMirror */ /* global define */ (function(mod) { 'use strict'; if (typeof exports === 'object' && typeof module === 'object') // CommonJS mod(require('../../lib/codemirror')); else if (typeof define === 'function' && define.amd) // AMD define(['../../lib/codemirror'], mod); else mod(CodeMirror); })(function(CodeMirror) { 'use strict'; var SearchOnly; CodeMirror.defineOption('searchonly', false, function(cm) { if (!SearchOnly){ SearchOnly = new SearchOnlyBox(cm); } }); function SearchOnlyBox(cm) { var self = this; var el = self.element = document; init(); function initElements(el) { self.searchBox = el.querySelector('.div-search'); self.searchInput = el.querySelector('.log-search'); } function init() { initElements(el); bindKeys(); self.$onChange = delayedCall(function() { self.find(false, false); }); el.addEventListener('click', function(e) { var t = e.target || e.srcElement; var action = t.getAttribute('action'); if (action && self[action]) self[action](); e.stopPropagation(); }); self.searchInput.addEventListener('input', function() { self.$onChange.schedule(20); }); self.searchInput.addEventListener('focus', function() { self.activeInput = self.searchInput; }); self.$onChange = delayedCall(function() { self.find(false, false); }); } function bindKeys() { var sb = self, obj = { 'Enter': function() { sb.findNext(); } }; self.element.addEventListener('keydown', function(event) { Object.keys(obj).some(function(name) { var is = key(name, event); if (is) { event.stopPropagation(); event.preventDefault(); obj[name](event); } return is; }); }); } this.find = function(skipCurrent, backwards) { var value = this.searchInput.value, options = { skipCurrent: skipCurrent, backwards: backwards }; find(value, options, function(searchCursor) { var current = searchCursor.matches(false, searchCursor.from()); cm.setSelection(current.from, current.to); }); }; this.findNext = function() { this.find(true, false); }; this.findPrev = function() { this.find(true, true); }; function find(value, options, callback) { var done, noMatch, searchCursor, next, prev, matches, cursor, position, val = value, o = options, is = true, caseSensitive = o.caseSensitive, regExp = o.regExp, wholeWord = o.wholeWord; if (regExp || wholeWord) { if (options.wholeWord) val = '\\b' + val + '\\b'; val = RegExp(val); } if (o.backwards) position = o.skipCurrent ? 'from': 'to'; else position = o.skipCurrent ? 'to' : 'from'; cursor = cm.getCursor(position); searchCursor = cm.getSearchCursor(val, cursor, !caseSensitive); next = searchCursor.findNext.bind(searchCursor), prev = searchCursor.findPrevious.bind(searchCursor), matches = searchCursor.matches.bind(searchCursor); if (o.backwards && !prev()) { is = next(); if (is) { cm.setCursor(cm.doc.size - 1, 0); find(value, options, callback); done = true; } } else if (!o.backwards && !next()) { is = prev(); if (is) { cm.setCursor(0, 0); find(value, options, callback); done = true; } } noMatch = !is && self.searchInput.value; setCssClass(self.searchInput, 'no_result_found', noMatch); if (!done && is) callback(searchCursor); } function setCssClass(el, className, condition) { var list = el.classList; list[condition ? 'add' : 'remove'](className); } function delayedCall(fcn, defaultTimeout) { var timer, callback = function() { timer = null; fcn(); }, _self = function(timeout) { if (!timer) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; } /* https://github.com/coderaiser/key */ function key(str, event) { var right, KEY = { BACKSPACE : 8, TAB : 9, ENTER : 13, ESC : 27, SPACE : 32, PAGE_UP : 33, PAGE_DOWN : 34, END : 35, HOME : 36, UP : 38, DOWN : 40, INSERT : 45, DELETE : 46, INSERT_MAC : 96, ASTERISK : 106, PLUS : 107, MINUS : 109, F1 : 112, F2 : 113, F3 : 114, F4 : 115, F5 : 116, F6 : 117, F7 : 118, F8 : 119, F9 : 120, F10 : 121, SLASH : 191, TRA : 192, /* Typewritten Reverse Apostrophe (`) */ BACKSLASH : 220 }; keyCheck(str, event); right = str.split('|').some(function(combination) { var wrong; wrong = combination.split('-').some(function(key) { var right; switch(key) { case 'Ctrl': right = event.ctrlKey; break; case 'Shift': right = event.shiftKey; break; case 'Alt': right = event.altKey; break; case 'Cmd': right = event.metaKey; break; default: if (key.length === 1) right = event.keyCode === key.charCodeAt(0); else Object.keys(KEY).some(function(name) { var up = key.toUpperCase(); if (up === name) right = event.keyCode === KEY[name]; }); break; } return !right; }); return !wrong; }); return right; } function keyCheck(str, event) { if (typeof str !== 'string') throw(Error('str should be string!')); if (typeof event !== 'object') throw(Error('event should be object!')); } } });
apache-2.0
ydai1124/gobblin-1
gobblin-api/src/main/java/gobblin/dataset/IterableDatasetFinder.java
1376
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gobblin.dataset; import java.io.IOException; import java.util.Iterator; /** * A {@link DatasetsFinder} that can return the {@link Dataset}s as an {@link Iterator}. This allows {@link Dataset}s * to be created on demand instead of all at once, possibly reducing memory usage and improving performance. */ public interface IterableDatasetFinder<T extends Dataset> extends DatasetsFinder<T> { /** * @return An {@link Iterator} over the {@link Dataset}s found. * @throws IOException */ public Iterator<T> getDatasetsIterator() throws IOException; }
apache-2.0
queeniema/incubator-edgent-website
site/javadoc/r1.1.0/org/apache/edgent/streamscope/mbeans/class-use/StreamScopeMXBean.html
10928
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Sun Feb 26 17:08:13 EST 2017 --> <title>Uses of Interface org.apache.edgent.streamscope.mbeans.StreamScopeMXBean (Edgent v1.1.0)</title> <meta name="date" content="2017-02-26"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.apache.edgent.streamscope.mbeans.StreamScopeMXBean (Edgent v1.1.0)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/edgent/streamscope/mbeans/class-use/StreamScopeMXBean.html" target="_top">Frames</a></li> <li><a href="StreamScopeMXBean.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.apache.edgent.streamscope.mbeans.StreamScopeMXBean" class="title">Uses of Interface<br>org.apache.edgent.streamscope.mbeans.StreamScopeMXBean</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.edgent.streamscope">org.apache.edgent.streamscope</a></td> <td class="colLast"> <div class="block">Stream Oscilloscope - package for instrumenting streams to capture tuples.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.apache.edgent.streamscope.mbeans">org.apache.edgent.streamscope.mbeans</a></td> <td class="colLast"> <div class="block">Stream Oscilloscope <a href="../../../../../../org/apache/edgent/execution/services/ControlService.html" title="interface in org.apache.edgent.execution.services"><code>ControlService</code></a> Management Bean interfaces.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.edgent.streamscope"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a> in <a href="../../../../../../org/apache/edgent/streamscope/package-summary.html">org.apache.edgent.streamscope</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/apache/edgent/streamscope/package-summary.html">org.apache.edgent.streamscope</a> that implement <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/edgent/streamscope/StreamScopeBean.html" title="class in org.apache.edgent.streamscope">StreamScopeBean</a></span></code> <div class="block">Implementation of <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans"><code>StreamScopeMXBean</code></a>.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/edgent/streamscope/package-summary.html">org.apache.edgent.streamscope</a> that return <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></code></td> <td class="colLast"><span class="typeNameLabel">StreamScopeRegistryBean.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/edgent/streamscope/StreamScopeRegistryBean.html#lookup-java.lang.String-java.lang.String-int-">lookup</a></span>(java.lang.String&nbsp;jobId, java.lang.String&nbsp;opletId, int&nbsp;oport)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.edgent.streamscope.mbeans"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a> in <a href="../../../../../../org/apache/edgent/streamscope/mbeans/package-summary.html">org.apache.edgent.streamscope.mbeans</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/edgent/streamscope/mbeans/package-summary.html">org.apache.edgent.streamscope.mbeans</a> that return <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">StreamScopeMXBean</a></code></td> <td class="colLast"><span class="typeNameLabel">StreamScopeRegistryMXBean.</span><code><span class="memberNameLink"><a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeRegistryMXBean.html#lookup-java.lang.String-java.lang.String-int-">lookup</a></span>(java.lang.String&nbsp;jobId, java.lang.String&nbsp;opletId, int&nbsp;oport)</code> <div class="block">Get the <a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans"><code>StreamScopeMXBean</code></a> registered for the specified stream</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/edgent/streamscope/mbeans/StreamScopeMXBean.html" title="interface in org.apache.edgent.streamscope.mbeans">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><a href="http://edgent.incubator.apache.org">Apache Edgent (incubating)</a></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/edgent/streamscope/mbeans/class-use/StreamScopeMXBean.html" target="_top">Frames</a></li> <li><a href="StreamScopeMXBean.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 The Apache Software Foundation. All Rights Reserved - 4744f56-20170226-1707</small></p> </body> </html>
apache-2.0
sachinpro/sachinpro.github.io
tensorflow/core/platform/demangle.h
1092
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_TENSORFLOW_CORE_PLATFORM_DEMANGLE_H_ #define THIRD_PARTY_TENSORFLOW_CORE_PLATFORM_DEMANGLE_H_ namespace tensorflow { namespace port { // If the compiler supports, demangle a mangled symbol name and return // the demangled name. Otherwise, returns 'mangled' as is. string Demangle(const char* mangled); } // namespace port } // namespace tensorflow #endif // THIRD_PARTY_TENSORFLOW_CORE_PLATFORM_DEMANGLE_H_
apache-2.0
tornadozou/tensorflow
tensorflow/core/kernels/conv_2d.h
11560
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_KERNELS_CONV_2D_H_ #define TENSORFLOW_KERNELS_CONV_2D_H_ #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/kernels/eigen_backward_spatial_convolutions.h" #include "tensorflow/core/kernels/eigen_spatial_convolutions.h" #include "tensorflow/core/util/tensor_format.h" namespace tensorflow { namespace functor { // TODO(yangke): revisit these operations and in particular, see if we can // combine all of them into just one operation without causing nvcc to // timeout. template <typename Device, typename T, int Dims, typename IndexType> struct ShuffleAndReverse { void operator()(const Device& d, typename TTypes<T, Dims, IndexType>::ConstTensor input, const Eigen::DSizes<IndexType, Dims>& order, const Eigen::array<bool, Dims>& reverse_dims, typename TTypes<T, Dims, IndexType>::Tensor output) { output.device(d) = input.shuffle(order).reverse(reverse_dims); } }; template <typename Device, typename T, int Dims, typename IndexType> struct InflatePadAndShuffle { void operator()( const Device& d, typename TTypes<T, Dims, IndexType>::ConstTensor input, const Eigen::DSizes<IndexType, Dims>& strides, const Eigen::array<Eigen::IndexPair<IndexType>, Dims>& pad_dims, const Eigen::DSizes<IndexType, Dims>& order, typename TTypes<T, Dims, IndexType>::Tensor output) { output.device(d) = input.inflate(strides).pad(pad_dims).shuffle(order); } }; template <typename Device, typename Input, typename Filter, typename Output> void SpatialConvolutionFunc(const Device& d, Output output, Input input, Filter filter, int row_stride, int col_stride, const Eigen::PaddingType& padding) { // Need to swap row/col when calling Eigen. output.device(d) = Eigen::SpatialConvolution(input, filter, col_stride, row_stride, padding); } template <typename Device, typename T> struct SpatialConvolution { void operator()(const Device& d, typename TTypes<T, 4>::Tensor output, typename TTypes<T, 4>::ConstTensor input, typename TTypes<T, 4>::ConstTensor filter, int row_stride, int col_stride, const Eigen::PaddingType& padding) { SpatialConvolutionFunc(d, output, input, filter, row_stride, col_stride, padding); } }; template <typename Device> struct SpatialConvolution<Device, Eigen::half> { void operator()(const Device& d, typename TTypes<Eigen::half, 4>::Tensor output, typename TTypes<Eigen::half, 4>::ConstTensor input, typename TTypes<Eigen::half, 4>::ConstTensor filter, int row_stride, int col_stride, const Eigen::PaddingType& padding) { output.device(d) = Eigen::SpatialConvolution(input.cast<float>(), filter.cast<float>(), col_stride, row_stride, padding) .cast<Eigen::half>(); } }; template <typename Device, typename T> struct SpatialConvolutionBackwardInput { void operator()(const Device& d, typename TTypes<T, 4>::Tensor input_backward, typename TTypes<T, 4>::ConstTensor kernel, typename TTypes<T, 4>::ConstTensor output_backward, int input_rows, int input_cols, int row_stride, int col_stride) { // Need to swap row/col when calling Eigen. input_backward.device(d) = Eigen::SpatialConvolutionBackwardInput( kernel, output_backward, input_cols, input_rows, col_stride, row_stride); } }; template <typename Device, typename T> struct SpatialConvolutionBackwardKernel { void operator()(const Device& d, typename TTypes<T, 4>::Tensor kernel_backward, typename TTypes<T, 4>::ConstTensor input, typename TTypes<T, 4>::ConstTensor output_backward, int kernel_rows, int kernel_cols, int row_stride, int col_stride) { // Need to swap row/col when calling Eigen. kernel_backward.device(d) = Eigen::SpatialConvolutionBackwardKernel( input, output_backward, kernel_cols, kernel_rows, col_stride, row_stride); } }; // TODO(vrv): Figure out how to use the MatMulFunctor in matmul_op.h. // My initial attempt to do this compiled but failed in the pytest // due to a swigdeps error. template <typename Device, typename T> struct MatMulConvFunctor { // Computes on device "d": out = in0 * in1, where * is matrix // multiplication. void operator()( const Device& d, typename TTypes<T, 2>::Tensor out, typename TTypes<T, 2>::ConstTensor in0, typename TTypes<T, 2>::ConstTensor in1, const Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1>& dim_pair) { out.device(d) = in0.contract(in1, dim_pair); } }; // Shuffles a filter tensor from: // [<spatial_dims>, in, out] // to: // [out, in, <spatial_dims>] template <typename Device, typename T, typename IndexType, int NDIMS> struct TransformFilter { void operator()(const Device& d, typename TTypes<T, NDIMS, IndexType>::ConstTensor in, typename TTypes<T, NDIMS, IndexType>::Tensor out) { // We want a 3, 2, 0, 1 shuffle. Merge the spatial dimensions together // to speed up the shuffle operation. Eigen::DSizes<IndexType, 3> merged_dims; merged_dims[0] = in.dimension(0); // spatial dimensions for (int i = 1; i < NDIMS - 2; ++i) { merged_dims[0] *= in.dimension(i); } merged_dims[1] = in.dimension(NDIMS - 2); // input filters merged_dims[2] = in.dimension(NDIMS - 1); // output filters Eigen::DSizes<IndexType, NDIMS> expanded_dims; expanded_dims[0] = in.dimension(NDIMS - 1); // output filters expanded_dims[1] = in.dimension(NDIMS - 2); // input filters for (int i = 0; i < NDIMS; ++i) { // spatial dimensions expanded_dims[i + 2] = in.dimension(i); } out.device(d) = in.reshape(merged_dims) .shuffle(Eigen::DSizes<IndexType, 3>(2, 1, 0)) .reshape(expanded_dims); } }; template <typename Device, typename T, typename IndexType> struct TransformDepth { void operator()(const Device& d, typename TTypes<T, 4, IndexType>::ConstTensor in, const Eigen::DSizes<IndexType, 4>& shuffle, typename TTypes<T, 4, IndexType>::Tensor out) { Eigen::DSizes<IndexType, 3> merged_dims; Eigen::DSizes<IndexType, 4> expanded_dims; Eigen::DSizes<IndexType, 3> new_shuffle; // Merge dimensions that won't be shuffled together to speed things up. if (shuffle[1] == 2 && shuffle[2] == 3) { merged_dims[0] = in.dimension(0); merged_dims[1] = in.dimension(1); merged_dims[2] = in.dimension(2) * in.dimension(3); new_shuffle[0] = shuffle[0]; new_shuffle[1] = 2; new_shuffle[2] = shuffle[3]; expanded_dims[0] = in.dimension(shuffle[0]); expanded_dims[1] = in.dimension(2); expanded_dims[2] = in.dimension(3); expanded_dims[3] = in.dimension(shuffle[3]); } else if (shuffle[0] == 2 && shuffle[1] == 3) { merged_dims[0] = in.dimension(0); merged_dims[1] = in.dimension(1); merged_dims[2] = in.dimension(2) * in.dimension(3); new_shuffle[0] = 2; new_shuffle[1] = shuffle[2]; new_shuffle[2] = shuffle[3]; expanded_dims[0] = in.dimension(2); expanded_dims[1] = in.dimension(3); expanded_dims[2] = in.dimension(shuffle[2]); expanded_dims[3] = in.dimension(shuffle[3]); } else if (shuffle[0] == 0 && shuffle[1] == 3 && shuffle[2] == 1 && shuffle[3] == 2) { merged_dims[0] = in.dimension(0); merged_dims[1] = in.dimension(1) * in.dimension(2); merged_dims[2] = in.dimension(3); new_shuffle[0] = 0; new_shuffle[1] = 2; new_shuffle[2] = 1; expanded_dims[0] = in.dimension(0); expanded_dims[1] = in.dimension(3); expanded_dims[2] = in.dimension(1); expanded_dims[3] = in.dimension(2); } else { assert(false && "unexpected shuffle"); } out.device(d) = in.reshape(merged_dims).shuffle(new_shuffle).reshape(expanded_dims); } }; template <typename Device, typename T, typename IndexType, int NDIMS> struct PadInput { void operator()(const Device& d, typename TTypes<T, NDIMS, IndexType>::ConstTensor in, const std::array<int, NDIMS - 2>& padding_left, const std::array<int, NDIMS - 2>& padding_right, typename TTypes<T, NDIMS, IndexType>::Tensor out, TensorFormat format) { Eigen::array<Eigen::IndexPair<IndexType>, NDIMS> padding; padding[GetTensorDimIndex<NDIMS - 2>(format, 'N')] = {0, 0}; for (int i = 0; i < NDIMS - 2; ++i) { padding[GetTensorDimIndex<NDIMS - 2>(format, '0' + i)] = { padding_left[i], padding_right[i]}; } padding[GetTensorDimIndex<NDIMS - 2>(format, 'C')] = {0, 0}; out.device(d) = in.pad(padding); } }; // Converts a tensor from: // [batch, <spatial>, filters] // to: // [batch, filters, <spatial>] template <typename Device, typename T, int NDIMS> struct NHWCToNCHW { void operator()(const Device& d, typename TTypes<T, NDIMS>::ConstTensor in, typename TTypes<T, NDIMS>::Tensor out); }; // Converts a tensor from: // [batch, filters, <spatial>] // to: // [batch, <spatial>, filters] template <typename Device, typename T, int NDIMS> struct NCHWToNHWC { void operator()(const Device& d, typename TTypes<T, NDIMS>::ConstTensor in, typename TTypes<T, NDIMS>::Tensor out); }; // Converts a tensor from: // [dim0, dim1, dim2] // to: // [dim0, dim2, dim1] template <typename Device, typename T> struct SwapDimension1And2InTensor3 { void operator()(const Device& d, const T* in, const gtl::ArraySlice<int64>& input_dims, T* out); }; // Converts a tensor from: // [dim0, dim1, dim2] // to: // [dim2, dim1, dim0] template <typename Device, typename T> struct SwapDimension0And2InTensor3 { void operator()(const Device& d, const T* in, const gtl::ArraySlice<int64>& input_dims, T* out); }; // Reverses the effect of TransformFilter above. template <typename Device, typename T, int NDIMS> struct ReverseTransformFilter { void operator()(const Device& d, typename TTypes<T, NDIMS>::ConstTensor in, typename TTypes<T, NDIMS>::Tensor out); }; } // namespace functor template <class T> class ConvAlgorithmMap; template <> class ConvAlgorithmMap<Eigen::ThreadPoolDevice> {}; } // namespace tensorflow #endif // TENSORFLOW_KERNELS_CONV_2D_H_
apache-2.0
bridgewell/kafka-net
src/kafka-net/KafkaTcpSocket.cs
17955
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; using System.Threading; using KafkaNet.Common; using KafkaNet.Model; using KafkaNet.Protocol; using KafkaNet.Statistics; namespace KafkaNet { /// <summary> /// The TcpSocket provides an abstraction from the main driver from having to handle connection to and reconnections with a server. /// The interface is intentionally limited to only read/write. All connection and reconnect details are handled internally. /// </summary> public class KafkaTcpSocket : IKafkaTcpSocket { public event Action OnServerDisconnected; public event Action<int> OnReconnectionAttempt; public event Action<int> OnReadFromSocketAttempt; public event Action<int> OnBytesReceived; public event Action<KafkaDataPayload> OnWriteToSocketAttempt; private const int DefaultReconnectionTimeout = 100; private const int DefaultReconnectionTimeoutMultiplier = 2; private const int MaxReconnectionTimeoutMinutes = 5; private readonly CancellationTokenSource _disposeToken = new CancellationTokenSource(); private readonly CancellationTokenRegistration _disposeRegistration; private readonly IKafkaLog _log; private readonly KafkaEndpoint _endpoint; private readonly TimeSpan _maximumReconnectionTimeout; private readonly AsyncCollection<SocketPayloadSendTask> _sendTaskQueue; private readonly AsyncCollection<SocketPayloadReadTask> _readTaskQueue; private readonly Task _socketTask; private readonly AsyncLock _clientLock = new AsyncLock(); private TcpClient _client; private int _disposeCount; /// <summary> /// Construct socket and open connection to a specified server. /// </summary> /// <param name="log">Logging facility for verbose messaging of actions.</param> /// <param name="endpoint">The IP endpoint to connect to.</param> /// <param name="maximumReconnectionTimeout">The maximum time to wait when backing off on reconnection attempts.</param> public KafkaTcpSocket(IKafkaLog log, KafkaEndpoint endpoint, TimeSpan? maximumReconnectionTimeout = null) { _log = log; _endpoint = endpoint; _maximumReconnectionTimeout = maximumReconnectionTimeout ?? TimeSpan.FromMinutes(MaxReconnectionTimeoutMinutes); _sendTaskQueue = new AsyncCollection<SocketPayloadSendTask>(); _readTaskQueue = new AsyncCollection<SocketPayloadReadTask>(); //dedicate a long running task to the read/write operations _socketTask = Task.Factory.StartNew(DedicatedSocketTask, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); _disposeRegistration = _disposeToken.Token.Register(() => { _sendTaskQueue.CompleteAdding(); _readTaskQueue.CompleteAdding(); }); } #region Interface Implementation... /// <summary> /// The IP Endpoint to the server. /// </summary> public KafkaEndpoint Endpoint { get { return _endpoint; } } /// <summary> /// Read a certain byte array size return only when all bytes received. /// </summary> /// <param name="readSize">The size in bytes to receive from server.</param> /// <returns>Returns a byte[] array with the size of readSize.</returns> public Task<byte[]> ReadAsync(int readSize) { return EnqueueReadTask(readSize, CancellationToken.None); } /// <summary> /// Read a certain byte array size return only when all bytes received. /// </summary> /// <param name="readSize">The size in bytes to receive from server.</param> /// <param name="cancellationToken">A cancellation token which will cancel the request.</param> /// <returns>Returns a byte[] array with the size of readSize.</returns> public Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken) { return EnqueueReadTask(readSize, cancellationToken); } /// <summary> /// Convenience function to write full buffer data to the server. /// </summary> /// <param name="payload">The buffer data to send.</param> /// <returns>Returns Task handle to the write operation with size of written bytes..</returns> public Task<KafkaDataPayload> WriteAsync(KafkaDataPayload payload) { return WriteAsync(payload, CancellationToken.None); } /// <summary> /// Write the buffer data to the server. /// </summary> /// <param name="payload">The buffer data to send.</param> /// <param name="cancellationToken">A cancellation token which will cancel the request.</param> /// <returns>Returns Task handle to the write operation with size of written bytes..</returns> public Task<KafkaDataPayload> WriteAsync(KafkaDataPayload payload, CancellationToken cancellationToken) { return EnqueueWriteTask(payload, cancellationToken); } #endregion private Task<KafkaDataPayload> EnqueueWriteTask(KafkaDataPayload payload, CancellationToken cancellationToken) { var sendTask = new SocketPayloadSendTask(payload, cancellationToken); _sendTaskQueue.Add(sendTask); StatisticsTracker.QueueNetworkWrite(_endpoint, payload); return sendTask.Tcp.Task; } private Task<byte[]> EnqueueReadTask(int readSize, CancellationToken cancellationToken) { var readTask = new SocketPayloadReadTask(readSize, cancellationToken); _readTaskQueue.Add(readTask); return readTask.Tcp.Task; } private void DedicatedSocketTask() { while (_disposeToken.IsCancellationRequested == false) { try { //block here until we can get connections then start loop pushing data through network stream var netStream = GetStreamAsync().Result; ProcessNetworkstreamTasks(netStream); } catch (Exception ex) { if (_disposeToken.IsCancellationRequested) { _log.WarnFormat("KafkaTcpSocket thread shutting down because of a dispose call."); var disposeException = new ObjectDisposedException("Object is disposing."); _sendTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); _readTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); return; } if (ex is ServerDisconnectedException) { if (OnServerDisconnected != null) OnServerDisconnected(); _log.ErrorFormat(ex.Message); continue; } _log.ErrorFormat("Exception occured in Socket handler task. Exception: {0}", ex); } } } private void ProcessNetworkstreamTasks(NetworkStream netStream) { Task writeTask = Task.FromResult(true); Task readTask = Task.FromResult(true); //reading/writing from network steam is not thread safe //Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. //As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference //between read and write threads and no synchronization is required. //https://msdn.microsoft.com/en-us/library/z2xae4f4.aspx while (_disposeToken.IsCancellationRequested == false && netStream != null) { Task sendDataReady = Task.WhenAll(writeTask, _sendTaskQueue.OnHasDataAvailable(_disposeToken.Token)); Task readDataReady = Task.WhenAll(readTask, _readTaskQueue.OnHasDataAvailable(_disposeToken.Token)); Task.WaitAny(sendDataReady, readDataReady); var exception = new[] { writeTask, readTask } .Where(x => x.IsFaulted && x.Exception != null) .SelectMany(x => x.Exception.InnerExceptions) .FirstOrDefault(); if (exception != null) throw exception; if (sendDataReady.IsCompleted) writeTask = ProcessSentTasksAsync(netStream, _sendTaskQueue.Pop()); if (readDataReady.IsCompleted) readTask = ProcessReadTaskAsync(netStream, _readTaskQueue.Pop()); } } private async Task ProcessReadTaskAsync(NetworkStream netStream, SocketPayloadReadTask readTask) { using (readTask) { try { StatisticsTracker.IncrementGauge(StatisticGauge.ActiveReadOperation); var readSize = readTask.ReadSize; var result = new List<byte>(readSize); var bytesReceived = 0; while (bytesReceived < readSize) { readSize = readSize - bytesReceived; var buffer = new byte[readSize]; if (OnReadFromSocketAttempt != null) OnReadFromSocketAttempt(readSize); bytesReceived = await netStream.ReadAsync(buffer, 0, readSize, readTask.CancellationToken) .WithCancellation(readTask.CancellationToken).ConfigureAwait(false); if (OnBytesReceived != null) OnBytesReceived(bytesReceived); if (bytesReceived <= 0) { using (_client) { _client = null; throw new ServerDisconnectedException(string.Format("Lost connection to server: {0}", _endpoint)); } } result.AddRange(buffer.Take(bytesReceived)); } readTask.Tcp.TrySetResult(result.ToArray()); } catch (Exception ex) { if (_disposeToken.IsCancellationRequested) { var exception = new ObjectDisposedException("Object is disposing."); readTask.Tcp.TrySetException(exception); throw exception; } if (ex is ServerDisconnectedException) { readTask.Tcp.TrySetException(ex); throw; } //if an exception made us lose a connection throw disconnected exception if (_client == null || _client.Connected == false) { var exception = new ServerDisconnectedException(string.Format("Lost connection to server: {0}", _endpoint)); readTask.Tcp.TrySetException(exception); throw exception; } readTask.Tcp.TrySetException(ex); throw; } finally { StatisticsTracker.DecrementGauge(StatisticGauge.ActiveReadOperation); } } } private async Task ProcessSentTasksAsync(NetworkStream netStream, SocketPayloadSendTask sendTask) { if (sendTask == null) return; using (sendTask) { var failed = false; var sw = Stopwatch.StartNew(); try { sw.Restart(); StatisticsTracker.IncrementGauge(StatisticGauge.ActiveWriteOperation); if (OnWriteToSocketAttempt != null) OnWriteToSocketAttempt(sendTask.Payload); await netStream.WriteAsync(sendTask.Payload.Buffer, 0, sendTask.Payload.Buffer.Length).ConfigureAwait(false); sendTask.Tcp.TrySetResult(sendTask.Payload); } catch (Exception ex) { failed = true; if (_disposeToken.IsCancellationRequested) { var exception = new ObjectDisposedException("Object is disposing."); sendTask.Tcp.TrySetException(exception); throw exception; } sendTask.Tcp.TrySetException(ex); throw; } finally { StatisticsTracker.DecrementGauge(StatisticGauge.ActiveWriteOperation); StatisticsTracker.CompleteNetworkWrite(sendTask.Payload, sw.ElapsedMilliseconds, failed); } } } private async Task<NetworkStream> GetStreamAsync() { //using a semaphore here to allow async waiting rather than blocking locks using (await _clientLock.LockAsync(_disposeToken.Token).ConfigureAwait(false)) { if ((_client == null || _client.Connected == false) && !_disposeToken.IsCancellationRequested) { _client = await ReEstablishConnectionAsync().ConfigureAwait(false); } return _client == null ? null : _client.GetStream(); } } /// <summary> /// (Re-)establish the Kafka server connection. /// Assumes that the caller has already obtained the <c>_clientLock</c> /// </summary> private async Task<TcpClient> ReEstablishConnectionAsync() { var attempts = 1; var reconnectionDelay = DefaultReconnectionTimeout; _log.WarnFormat("No connection to:{0}. Attempting to connect...", _endpoint); _client = null; while (_disposeToken.IsCancellationRequested == false) { try { if (OnReconnectionAttempt != null) OnReconnectionAttempt(attempts++); _client = new TcpClient(); await _client.ConnectAsync(_endpoint.Endpoint.Address, _endpoint.Endpoint.Port).ConfigureAwait(false); _log.WarnFormat("Connection established to:{0}.", _endpoint); return _client; } catch { reconnectionDelay = reconnectionDelay * DefaultReconnectionTimeoutMultiplier; reconnectionDelay = Math.Min(reconnectionDelay, (int)_maximumReconnectionTimeout.TotalMilliseconds); _log.WarnFormat("Failed connection to:{0}. Will retry in:{1}", _endpoint, reconnectionDelay); } await Task.Delay(TimeSpan.FromMilliseconds(reconnectionDelay), _disposeToken.Token).ConfigureAwait(false); } return _client; } public void Dispose() { if (Interlocked.Increment(ref _disposeCount) != 1) return; if (_disposeToken != null) _disposeToken.Cancel(); using (_disposeToken) using (_disposeRegistration) using (_client) using (_socketTask) { _socketTask.SafeWait(TimeSpan.FromSeconds(30)); } } } class SocketPayloadReadTask : IDisposable { public CancellationToken CancellationToken { get; private set; } public TaskCompletionSource<byte[]> Tcp { get; set; } public int ReadSize { get; set; } private readonly CancellationTokenRegistration _cancellationTokenRegistration; public SocketPayloadReadTask(int readSize, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Tcp = new TaskCompletionSource<byte[]>(); ReadSize = readSize; _cancellationTokenRegistration = cancellationToken.Register(() => Tcp.TrySetCanceled()); } public void Dispose() { using (_cancellationTokenRegistration) { } } } class SocketPayloadSendTask : IDisposable { public TaskCompletionSource<KafkaDataPayload> Tcp { get; set; } public KafkaDataPayload Payload { get; set; } private readonly CancellationTokenRegistration _cancellationTokenRegistration; public SocketPayloadSendTask(KafkaDataPayload payload, CancellationToken cancellationToken) { Tcp = new TaskCompletionSource<KafkaDataPayload>(); Payload = payload; _cancellationTokenRegistration = cancellationToken.Register(() => Tcp.TrySetCanceled()); } public void Dispose() { using (_cancellationTokenRegistration) { } } } public class KafkaDataPayload { public int CorrelationId { get; set; } public ApiKeyRequestType ApiKey { get; set; } public int MessageCount { get; set; } public bool TrackPayload { get { return MessageCount > 0; } } public byte[] Buffer { get; set; } } }
apache-2.0
jboss-integration/kie-uberfire-extensions
i18n-taglib/src/main/java/org/apache/taglibs/i18n/IfndefTag.java
2046
/* * Copyright 1999,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.taglibs.i18n; import java.io.IOException; import java.util.ResourceBundle; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.BodyTagSupport; /** * This class implements body tag that allows you to use a resource bundle * to internationalize content in a web page. If a value is found in the * resource bundle for the required "key" attribute, then the enclosed JSP * is evaluated, otherwise, it is skipped. * <P> * The ifdef and ifndef tags allow the JSP author to conditionally evaluate * sections of a JSP based on whether or not a value is provided for the * given key. * <P> * <H2>Examples</H2> * <PRE> * &lt;i18n:bundle baseName="test"/&gt; * &lt;i18n:ifndef key="test"&gt; * misc html and jsp * &lt;/i18n:ifndef&gt; * etc... * </PRE> * <P> * * @author <a href="mailto:[email protected]">Tim Dawson</a> * */ public class IfndefTag extends ConditionalTagSupport { protected static final String _tagname = "i18n:ifndef"; /** * locates the bundle and tests whether the key has a value */ public boolean shouldEvaluate() throws JspException { String value = this.getValue(); if ( value == null || value.length() == 0 ) { return true; } else { return false; } } }
apache-2.0
jamesadevine/mbed
libraries/mbed/targets/hal/TARGET_Atmel/TARGET_SAM21/drivers/dma/dma.h
27057
#ifndef DMA_H_INCLUDED #define DMA_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /** * \defgroup asfdoc_sam0_dma_group SAM Direct Memory Access Controller Driver (DMAC) * * This driver for Atmel庐 | SMART SAM devices provides an interface for the configuration * and management of the Direct Memory Access Controller(DMAC) module within * the device. The DMAC can transfer data between memories and peripherals, and * thus off-load these tasks from the CPU. The module supports peripheral to * peripheral, peripheral to memory, memory to peripheral, and memory to memory * transfers. * * The following peripherals are used by the DMAC Driver: * - DMAC (Direct Memory Access Controller) * * The following devices can use this module: * - Atmel | SMART SAM D21 * - Atmel | SMART SAM R21 * - Atmel | SMART SAM D10/D11 * - Atmel | SMART SAM L21 * * The outline of this documentation is as follows: * - \ref asfdoc_sam0_dma_prerequisites * - \ref asfdoc_sam0_dma_module_overview * - \ref asfdoc_sam0_dma_special_considerations * - \ref asfdoc_sam0_dma_extra_info * - \ref asfdoc_sam0_dma_examples * - \ref asfdoc_sam0_dma_api_overview * * * \section asfdoc_sam0_dma_prerequisites Prerequisites * * There are no prerequisites for this module. * * * \section asfdoc_sam0_dma_module_overview Module Overview * * SAM devices with DMAC enables high data transfer rates with minimum * CPU intervention and frees up CPU time. With access to all peripherals, * the DMAC can handle automatic transfer of data to/from modules. * It supports static and incremental addressing for both source and * destination. * * The DMAC when used with Event System or peripheral triggers, provides a * considerable advantage by reducing the power consumption and performing * data transfer in the background. * For example if the ADC is configured to generate an event, it can trigger * the DMAC to transfer the data into another peripheral or into SRAM. * The CPU can remain in sleep during this time to reduce power consumption. * * The DMAC module has 12 channels. The DMA channel * operation can be suspended at any time by software, by events * from event system, or after selectable descriptor execution. The operation * can be resumed by software or by events from event system. * The DMAC driver for SAM supports four types of transfers such as * peripheral to peripheral, peripheral to memory, memory to peripheral, and * memory to memory. * * The basic transfer unit is a beat which is defined as a single bus access. * There can be multiple beats in a single block transfer and multiple block * transfers in a DMA transaction. * DMA transfer is based on descriptors, which holds transfer properties * such as the source and destination addresses, transfer counter, and other * additional transfer control information. * The descriptors can be static or linked. When static, a single block transfer * is performed. When linked, a number of transfer descriptors can be used to * enable multiple block transfers within a single DMA transaction. * * The implementation of the DMA driver is based on the idea that DMA channel * is a finite resource of entities with the same abilities. A DMA channel resource * is able to move a defined set of data from a source address to destination * address triggered by a transfer trigger. On the SAM devices there are 12 * DMA resources available for allocation. Each of these DMA resources can trigger * interrupt callback routines and peripheral events. * The other main features are * * - Selectable transfer trigger source * - Software * - Event System * - Peripheral * - Event input and output is supported for the four lower channels * - Four level channel priority * - Optional interrupt generation on transfer complete, channel error or channel suspend * - Supports multi-buffer or circular buffer mode by linking multiple descriptors * - Beat size configurable as 8-bit, 16-bit, or 32-bit * * A simplified block diagram of the DMA Resource can be seen in * \ref asfdoc_sam0_dma_module_block_diagram "the figure below". * * \anchor asfdoc_sam0_dma_module_block_diagram * \dot * digraph overview { * splines = false; * rankdir=LR; * * mux1 [label="Transfer Trigger", shape=box]; * * dma [label="DMA Channel", shape=polygon, sides=6, orientation=60, style=filled, fillcolor=darkolivegreen1, height=1, width=1]; * descriptor [label="Transfer Descriptor", shape=box, style=filled, fillcolor=lightblue]; * * mux1 -> dma; * descriptor -> dma; * * interrupt [label="Interrupt", shape=box]; * events [label="Events", shape=box]; * * dma:e -> interrupt:w; * dma:e -> events:w; * * {rank=same; descriptor dma} * * } * \enddot * * \subsection asfdoc_sam0_dma_features Driver Feature Macro Definition * <table> * <tr> * <th>Driver Feature Macro</th> * <th>Supported devices</th> * </tr> * <tr> * <td>FEATURE_DMA_CHANNEL_STANDBY</td> * <td>SAML21</td> * </tr> * </table> * \note The specific features are only available in the driver when the * selected device supports those features. * * \subsection asfdoc_sam0_dma_module_overview_dma_transf_term Terminology Used in DMAC Transfers * * <table border="0" cellborder="1" cellspacing="0" > * <tr> * <th> Name </th> <th> Description </th> * </tr> * <tr> * <td > Beat </td> * <td > It is a single bus access by the DMAC. * Configurable as 8-bit, 16-bit, or 32-bit * </td> * </tr> * <tr> * <td > Burst </td> * <td> It is a transfer of n-beats (n=1,4,8,16). * For the DMAC module in SAM, the burst size is one beat. * Arbitration takes place each time a burst transfer is completed * </td> * </tr> * <tr> * <td > Block transfer </td> * <td> A single block transfer is a configurable number of (1 to 64k) * beat transfers * </td> * </tr> * </table> * * \subsection asfdoc_sam0_dma_module_overview_dma_channels DMA Channels * The DMAC in each device consists of several DMA channels, which * along with the transfer descriptors defines the data transfer properties. * - The transfer control descriptor defines the source and destination * addresses, source and destination address increment settings, the * block transfer count and event output condition selection * - Dedicated channel registers control the peripheral trigger source, * trigger mode settings, event input actions, and channel priority level * settings * * With a successful DMA resource allocation, a dedicated * DMA channel will be assigned. The channel will be occupied until the * DMA resource is freed. A DMA resource handle is used to identify the specific * DMA resource. * When there are multiple channels with active requests, the arbiter prioritizes * the channels requesting access to the bus. * * \subsection asfdoc_sam0_dma_module_overview_dma_trigger DMA Triggers * DMA transfer can be started only when a DMA transfer request is acknowledged/granted by the arbiter. A * transfer request can be triggered from software, peripheral, or an event. There * are dedicated source trigger selections for each DMA channel usage. * * \subsection asfdoc_sam0_dma_module_overview_dma_transfer_descriptor DMA Transfer Descriptor * The transfer descriptor resides in the SRAM and * defines these channel properties. * <table border="0" cellborder="1" cellspacing="0" > * <tr> * <th> Field name </th> <th> Field width </th> * </tr> * <tr> * <td > Descriptor Next Address </td> <td > 32 bits </td> * </tr> * <tr> * <td > Destination Address </td> <td> 32 bits </td> * </tr> * <tr> * <td > Source Address </td> <td> 32 bits </td> * </tr> * <tr> * <td > Block Transfer Counter </td> <td> 16 bits </td> * </tr> * <tr> * <td > Block Transfer Control </td> <td> 16 bits </td> * </tr> * </table> * * Before starting a transfer, at least one descriptor should be configured. * After a successful allocation of a DMA channel, the transfer descriptor can * be added with a call to \ref dma_add_descriptor(). If there is a transfer * descriptor already allocated to the DMA resource, the descriptor will * be linked to the next descriptor address. * * \subsection asfdoc_sam0_dma_module_overview_dma_output DMA Interrupts/Events * Both an interrupt callback and an peripheral event can be triggered by the * DMA transfer. Three types of callbacks are supported by the DMA driver: * transfer complete, channel suspend, and transfer error. Each of these callback * types can be registered and enabled for each channel independently through * the DMA driver API. * * The DMAC module can also generate events on transfer complete. Event * generation is enabled through the DMA channel, event channel configuration, * and event user multiplexing is done through the events driver. * * The DMAC can generate events in the below cases: * * - When a block transfer is complete * * - When each beat transfer within a block transfer is complete * * \section asfdoc_sam0_dma_special_considerations Special Considerations * * There are no special considerations for this module. * * * \section asfdoc_sam0_dma_extra_info Extra Information * * For extra information, see \ref asfdoc_sam0_dma_extra. This includes: * - \ref asfdoc_sam0_dma_extra_acronyms * - \ref asfdoc_sam0_dma_extra_dependencies * - \ref asfdoc_sam0_dma_extra_errata * - \ref asfdoc_sam0_dma_extra_history * * * \section asfdoc_sam0_dma_examples Examples * * For a list of examples related to this driver, see * \ref asfdoc_sam0_dma_exqsg. * * * \section asfdoc_sam0_dma_api_overview API Overview * @{ */ #include <compiler.h> #include "conf_dma.h" #if (SAML21) #define FEATURE_DMA_CHANNEL_STANDBY #endif /** DMA invalid channel number. */ #define DMA_INVALID_CHANNEL 0xff /** ExInitial description section. */ extern DmacDescriptor descriptor_section[CONF_MAX_USED_CHANNEL_NUM]; /** DMA priority level. */ enum dma_priority_level { /** Priority level 0. */ DMA_PRIORITY_LEVEL_0, /** Priority level 1. */ DMA_PRIORITY_LEVEL_1, /** Priority level 2. */ DMA_PRIORITY_LEVEL_2, /** Priority level 3. */ DMA_PRIORITY_LEVEL_3, }; /** DMA input actions. */ enum dma_event_input_action { /** No action. */ DMA_EVENT_INPUT_NOACT, /** Normal transfer and periodic transfer trigger. */ DMA_EVENT_INPUT_TRIG, /** Conditional transfer trigger. */ DMA_EVENT_INPUT_CTRIG, /** Conditional block transfer. */ DMA_EVENT_INPUT_CBLOCK, /** Channel suspend operation. */ DMA_EVENT_INPUT_SUSPEND, /** Channel resume operation. */ DMA_EVENT_INPUT_RESUME, /** Skip next block suspend action. */ DMA_EVENT_INPUT_SSKIP, }; /** * Address increment step size. These bits select the address increment step * size. The setting apply to source or destination address, depending on * STEPSEL setting. */ enum dma_address_increment_stepsize { /** The address is incremented by (beat size * 1). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_1 = 0, /** The address is incremented by (beat size * 2). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_2, /** The address is incremented by (beat size * 4). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_4, /** The address is incremented by (beat size * 8). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_8, /** The address is incremented by (beat size * 16). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_16, /** The address is incremented by (beat size * 32). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_32, /** The address is incremented by (beat size * 64). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_64, /** The address is incremented by (beat size * 128). */ DMA_ADDRESS_INCREMENT_STEP_SIZE_128, }; /** * DMA step selection. This bit determines whether the step size setting * is applied to source or destination address. */ enum dma_step_selection { /** Step size settings apply to the destination address. */ DMA_STEPSEL_DST = 0, /** Step size settings apply to the source address. */ DMA_STEPSEL_SRC, }; /** The basic transfer unit in DMAC is a beat, which is defined as a * single bus access. Its size is configurable and applies to both read * and write. */ enum dma_beat_size { /** 8-bit access. */ DMA_BEAT_SIZE_BYTE = 0, /** 16-bit access. */ DMA_BEAT_SIZE_HWORD, /** 32-bit access. */ DMA_BEAT_SIZE_WORD, }; /** * Block action definitions. */ enum dma_block_action { /** No action. */ DMA_BLOCK_ACTION_NOACT = 0, /** Channel in normal operation and sets transfer complete interrupt flag * after block transfer. */ DMA_BLOCK_ACTION_INT, /** Trigger channel suspend after block transfer and sets channel * suspend interrupt flag once the channel is suspended. */ DMA_BLOCK_ACTION_SUSPEND, /** Sets transfer complete interrupt flag after a block transfer and * trigger channel suspend. The channel suspend interrupt flag will be set * once the channel is suspended. */ DMA_BLOCK_ACTION_BOTH, }; /** Event output selection. */ enum dma_event_output_selection { /** Event generation disable. */ DMA_EVENT_OUTPUT_DISABLE = 0, /** Event strobe when block transfer complete. */ DMA_EVENT_OUTPUT_BLOCK, /** Event output reserved. */ DMA_EVENT_OUTPUT_RESERVED, /** Event strobe when beat transfer complete. */ DMA_EVENT_OUTPUT_BEAT, }; /** DMA trigger action type. */ enum dma_transfer_trigger_action { /** Perform a block transfer when triggered. */ DMA_TRIGGER_ACTON_BLOCK = DMAC_CHCTRLB_TRIGACT_BLOCK_Val, /** Perform a beat transfer when triggered. */ DMA_TRIGGER_ACTON_BEAT = DMAC_CHCTRLB_TRIGACT_BEAT_Val, /** Perform a transaction when triggered. */ DMA_TRIGGER_ACTON_TRANSACTION = DMAC_CHCTRLB_TRIGACT_TRANSACTION_Val, }; /** * Callback types for DMA callback driver. */ enum dma_callback_type { /** Callback for transfer complete. */ DMA_CALLBACK_TRANSFER_DONE, /** Callback for any of transfer errors. A transfer error is flagged * if a bus error is detected during an AHB access or when the DMAC * fetches an invalid descriptor. */ DMA_CALLBACK_TRANSFER_ERROR, /** Callback for channel suspend. */ DMA_CALLBACK_CHANNEL_SUSPEND, /** Number of available callbacks. */ DMA_CALLBACK_N, }; /** * DMA transfer descriptor configuration. When the source or destination address * increment is enabled, the addresses stored into the configuration structure * must correspond to the end of the transfer. * */ struct dma_descriptor_config { /** Descriptor valid flag used to identify whether a descriptor is valid or not. */ bool descriptor_valid; /** This is used to generate an event on specific transfer action in a channel. Supported only in four lower channels. */ enum dma_event_output_selection event_output_selection; /** Action taken when a block transfer is completed. */ enum dma_block_action block_action; /** Beat size is configurable as 8-bit, 16-bit, or 32-bit. */ enum dma_beat_size beat_size; /** Used for enabling the source address increment. */ bool src_increment_enable; /** Used for enabling the destination address increment. */ bool dst_increment_enable; /** This bit selects whether the source or destination address is using the step size settings. */ enum dma_step_selection step_selection; /** The step size for source/destination address increment. The next address is calculated as next_addr = addr + (2^step_size * beat size). */ enum dma_address_increment_stepsize step_size; /** It is the number of beats in a block. This count value is * decremented by one after each beat data transfer. */ uint16_t block_transfer_count; /** Transfer source address. */ uint32_t source_address; /** Transfer destination address. */ uint32_t destination_address; /** Set to zero for static descriptors. This must have a valid memory address for linked descriptors. */ uint32_t next_descriptor_address; }; /** Configurations for DMA events. */ struct dma_events_config { /** Event input actions. */ enum dma_event_input_action input_action; /** Enable DMA event output. */ bool event_output_enable; }; /** DMA configurations for transfer. */ struct dma_resource_config { /** DMA transfer priority. */ enum dma_priority_level priority; /**DMA peripheral trigger index. */ uint8_t peripheral_trigger; /** DMA trigger action. */ enum dma_transfer_trigger_action trigger_action; #ifdef FEATURE_DMA_CHANNEL_STANDBY /** Keep DMA channel enabled in standby sleep mode if true. */ bool run_in_standby; #endif /** DMA events configurations. */ struct dma_events_config event_config; }; /** Forward definition of the DMA resource. */ struct dma_resource; /** Type definition for a DMA resource callback function. */ typedef void (*dma_callback_t)(const struct dma_resource *const resource); /** Structure for DMA transfer resource. */ struct dma_resource { /** Allocated DMA channel ID. */ uint8_t channel_id; /** Array of callback functions for DMA transfer job. */ dma_callback_t callback[DMA_CALLBACK_N]; /** Bit mask for enabled callbacks. */ uint8_t callback_enable; /** Status of the last job. */ volatile enum status_code job_status; /** Transferred data size. */ uint32_t transfered_size; /** DMA transfer descriptor. */ DmacDescriptor* descriptor; }; /** * \brief Get DMA resource status. * * \param[in] resource Pointer to the DMA resource * * \return Status of the DMA resource. */ static inline enum status_code dma_get_job_status(struct dma_resource *resource) { Assert(resource); return resource->job_status; } /** * \brief Check if the given DMA resource is busy. * * \param[in] resource Pointer to the DMA resource * * \return Status which indicates whether the DMA resource is busy. * * \retval true The DMA resource has an on-going transfer * \retval false The DMA resource is not busy */ static inline bool dma_is_busy(struct dma_resource *resource) { Assert(resource); return (resource->job_status == STATUS_BUSY); } /** * \brief Enable a callback function for a dedicated DMA resource. * * \param[in] resource Pointer to the DMA resource * \param[in] type Callback function type * */ static inline void dma_enable_callback(struct dma_resource *resource, enum dma_callback_type type) { Assert(resource); resource->callback_enable |= 1 << type; } /** * \brief Disable a callback function for a dedicated DMA resource. * * \param[in] resource Pointer to the DMA resource * \param[in] type Callback function type * */ static inline void dma_disable_callback(struct dma_resource *resource, enum dma_callback_type type) { Assert(resource); resource->callback_enable &= ~(1 << type); } /** * \brief Register a callback function for a dedicated DMA resource. * * There are three types of callback functions, which can be registered: * - Callback for transfer complete * - Callback for transfer error * - Callback for channel suspend * * \param[in] resource Pointer to the DMA resource * \param[in] callback Pointer to the callback function * \param[in] type Callback function type * */ static inline void dma_register_callback(struct dma_resource *resource, dma_callback_t callback, enum dma_callback_type type) { Assert(resource); resource->callback[type] = callback; } /** * \brief Unregister a callback function for a dedicated DMA resource. * * There are three types of callback functions: * - Callback for transfer complete * - Callback for transfer error * - Callback for channel suspend * * The application can unregister any of the callback functions which * are already registered and are no longer needed. * * \param[in] resource Pointer to the DMA resource * \param[in] type Callback function type * */ static inline void dma_unregister_callback(struct dma_resource *resource, enum dma_callback_type type) { Assert(resource); resource->callback[type] = NULL; } /** * \brief Will set a software trigger for resource. * * This function is used to set a software trigger on the DMA channel * associated with resource. If a trigger is already pending no new trigger * will be generated for the channel. * * \param[in] resource Pointer to the DMA resource */ static inline void dma_trigger_transfer(struct dma_resource *resource) { Assert(resource); DMAC->SWTRIGCTRL.reg |= (1 << resource->channel_id); } /** * \brief Initializes DMA transfer configuration with predefined default values. * * This function will initialize a given DMA descriptor configuration structure to * a set of known default values. This function should be called on * any new instance of the configuration structure before being * modified by the user application. * * The default configuration is as follows: * \li Set the descriptor as valid * \li Disable event output * \li No block action * \li Set beat size as byte * \li Enable source increment * \li Enable destination increment * \li Step size is applied to the destination address * \li Address increment is beat size multiplied by 1 * \li Default transfer size is set to 0 * \li Default source address is set to NULL * \li Default destination address is set to NULL * \li Default next descriptor not available * \param[out] config Pointer to the configuration * */ static inline void dma_descriptor_get_config_defaults(struct dma_descriptor_config *config) { Assert(config); /* Set descriptor as valid */ config->descriptor_valid = true; /* Disable event output */ config->event_output_selection = DMA_EVENT_OUTPUT_DISABLE; /* No block action */ config->block_action = DMA_BLOCK_ACTION_NOACT; /* Set beat size to one byte */ config->beat_size = DMA_BEAT_SIZE_BYTE; /* Enable source increment */ config->src_increment_enable = true; /* Enable destination increment */ config->dst_increment_enable = true; /* Step size is applied to the destination address */ config->step_selection = DMA_STEPSEL_DST; /* Address increment is beat size multiplied by 1*/ config->step_size = DMA_ADDRESS_INCREMENT_STEP_SIZE_1; /* Default transfer size is set to 0 */ config->block_transfer_count = 0; /* Default source address is set to NULL */ config->source_address = (uint32_t)NULL; /* Default destination address is set to NULL */ config->destination_address = (uint32_t)NULL; /** Next descriptor address set to 0 */ config->next_descriptor_address = 0; } /** * \brief Update DMA descriptor. * * This function can update the descriptor of an allocated DMA resource. * */ static inline void dma_update_descriptor(struct dma_resource *resource, DmacDescriptor* descriptor) { Assert(resource); resource->descriptor = descriptor; } /** * \brief Reset DMA descriptor. * * This function will clear the DESCADDR register of an allocated DMA resource. * */ static inline void dma_reset_descriptor(struct dma_resource *resource) { Assert(resource); resource->descriptor = NULL; } void dma_get_config_defaults(struct dma_resource_config *config); enum status_code dma_allocate(struct dma_resource *resource, struct dma_resource_config *config); enum status_code dma_free(struct dma_resource *resource); enum status_code dma_start_transfer_job(struct dma_resource *resource); void dma_abort_job(struct dma_resource *resource); void dma_suspend_job(struct dma_resource *resource); void dma_resume_job(struct dma_resource *resource); void dma_descriptor_create(DmacDescriptor* descriptor, struct dma_descriptor_config *config); enum status_code dma_add_descriptor(struct dma_resource *resource, DmacDescriptor* descriptor); /** @} */ /** * \page asfdoc_sam0_dma_extra Extra Information for DMAC Driver * * \section asfdoc_sam0_dma_extra_acronyms Acronyms * Below is a table listing the acronyms used in this module, along with their * intended meanings. * * <table> * <tr> * <th>Acronym</th> * <th>Description</th> * </tr> * <tr> * <td>DMA</td> * <td>Direct Memory Access</td> * </tr> * <tr> * <td>DMAC</td> * <td>Direct Memory Access Controller </td> * </tr> * <tr> * <td>CPU</td> * <td>Central Processing Unit</td> * </tr> * </table> * * * \section asfdoc_sam0_dma_extra_dependencies Dependencies * This driver has the following dependencies: * * - \ref asfdoc_sam0_system_clock_group "System Clock Driver" * * * \section asfdoc_sam0_dma_extra_errata Errata * There are no errata related to this driver. * * * \section asfdoc_sam0_dma_extra_history Module History * An overview of the module history is presented in the table below, with * details on the enhancements and fixes made to the module since its first * release. The current version of this corresponds to the newest version in * the table. * * <table> * <tr> * <th>Changelog</th> * </tr> * <tr> * <td>Add SAM L21 support</td> * </tr> * <tr> * <td>Initial Release</td> * </tr> * </table> */ /** * \page asfdoc_sam0_dma_exqsg Examples for DMAC Driver * * This is a list of the available Quick Start Guides (QSGs) and example * applications for \ref asfdoc_sam0_dma_group. QSGs are simple examples with * step-by-step instructions to configure and use this driver in a selection of * use cases. Note that QSGs can be compiled as a standalone application or be * added to the user application. * * - \subpage asfdoc_sam0_dma_basic_use_case * * \note More DMA usage examples are available in peripheral QSGs. * A quick start guide for TC/TCC * shows the usage of DMA event trigger; SERCOM SPI/USART/I<SUP>2</SUP>C has example for * DMA transfer from peripheral to memory or from memory to peripheral; * ADC/DAC shows peripheral to peripheral transfer. * * \page asfdoc_sam0_dma_document_revision_history Document Revision History * * <table> * <tr> * <th>Doc. Rev.</td> * <th>Date</td> * <th>Comments</td> * </tr> * <tr> * <td>C</td> * <td>11/2014</td> * <td>Added SAML21 support</td> * </tr> * <tr> * <td>B</td> * <td>12/2014</td> * <td>Added SAMR21 and SAMD10/D11 support</td> * </tr> * <tr> * <td>A</td> * <td>02/2014</td> * <td>Initial release</td> * </tr> * </table> */ #ifdef __cplusplus } #endif #endif /* DMA_H_INCLUDED */
apache-2.0
strapdata/elassandra
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java
30153
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.ssl; import org.elasticsearch.common.CharArrays; import javax.crypto.Cipher; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.interfaces.ECKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPrivateKeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; final class PemUtils { private static final String PKCS1_HEADER = "-----BEGIN RSA PRIVATE KEY-----"; private static final String PKCS1_FOOTER = "-----END RSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_HEADER = "-----BEGIN DSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_FOOTER = "-----END DSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_PARAMS_HEADER ="-----BEGIN DSA PARAMETERS-----"; private static final String OPENSSL_DSA_PARAMS_FOOTER ="-----END DSA PARAMETERS-----"; private static final String PKCS8_HEADER = "-----BEGIN PRIVATE KEY-----"; private static final String PKCS8_FOOTER = "-----END PRIVATE KEY-----"; private static final String PKCS8_ENCRYPTED_HEADER = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; private static final String PKCS8_ENCRYPTED_FOOTER = "-----END ENCRYPTED PRIVATE KEY-----"; private static final String OPENSSL_EC_HEADER = "-----BEGIN EC PRIVATE KEY-----"; private static final String OPENSSL_EC_FOOTER = "-----END EC PRIVATE KEY-----"; private static final String OPENSSL_EC_PARAMS_HEADER = "-----BEGIN EC PARAMETERS-----"; private static final String OPENSSL_EC_PARAMS_FOOTER = "-----END EC PARAMETERS-----"; private static final String HEADER = "-----BEGIN"; private PemUtils() { throw new IllegalStateException("Utility class should not be instantiated"); } /** * Creates a {@link PrivateKey} from the contents of a file. Supports PKCS#1, PKCS#8 * encoded formats of encrypted and plaintext RSA, DSA and EC(secp256r1) keys * * @param keyPath the path for the key file * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return a private key from the contents of the file */ public static PrivateKey readPrivateKey(Path keyPath, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { try (BufferedReader bReader = Files.newBufferedReader(keyPath, StandardCharsets.UTF_8)) { String line = bReader.readLine(); while (null != line && line.startsWith(HEADER) == false) { line = bReader.readLine(); } if (null == line) { throw new SslConfigException("Error parsing Private Key [" + keyPath.toAbsolutePath() + "], file is empty"); } if (PKCS8_ENCRYPTED_HEADER.equals(line.trim())) { char[] password = passwordSupplier.get(); if (password == null) { throw new SslConfigException("cannot read encrypted key [" + keyPath.toAbsolutePath() + "] without a password"); } return parsePKCS8Encrypted(bReader, password); } else if (PKCS8_HEADER.equals(line.trim())) { return parsePKCS8(bReader); } else if (PKCS1_HEADER.equals(line.trim())) { return parsePKCS1Rsa(bReader, passwordSupplier); } else if (OPENSSL_DSA_HEADER.equals(line.trim())) { return parseOpenSslDsa(bReader, passwordSupplier); } else if (OPENSSL_DSA_PARAMS_HEADER.equals(line.trim())) { return parseOpenSslDsa(removeDsaHeaders(bReader), passwordSupplier); } else if (OPENSSL_EC_HEADER.equals(line.trim())) { return parseOpenSslEC(bReader, passwordSupplier); } else if (OPENSSL_EC_PARAMS_HEADER.equals(line.trim())) { return parseOpenSslEC(removeECHeaders(bReader), passwordSupplier); } else { throw new SslConfigException("error parsing Private Key [" + keyPath.toAbsolutePath() + "], file does not contain a supported key format"); } } catch (FileNotFoundException | NoSuchFileException e) { throw new SslConfigException("private key file [" + keyPath.toAbsolutePath() + "] does not exist", e); } catch (IOException | GeneralSecurityException e) { throw new SslConfigException("private key file [" + keyPath.toAbsolutePath() + "] cannot be parsed", e); } } /** * Removes the EC Headers that OpenSSL adds to EC private keys as the information in them * is redundant * * @throws IOException if the EC Parameter footer is missing */ private static BufferedReader removeECHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_EC_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line || OPENSSL_EC_PARAMS_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, EC Parameters footer is missing"); } // Verify that the key starts with the correct header before passing it to parseOpenSslEC if (OPENSSL_EC_HEADER.equals(bReader.readLine()) == false) { throw new IOException("Malformed PEM file, EC Key header is missing"); } return bReader; } /** * Removes the DSA Params Headers that OpenSSL adds to DSA private keys as the information in them * is redundant * * @throws IOException if the EC Parameter footer is missing */ private static BufferedReader removeDsaHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_DSA_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line || OPENSSL_DSA_PARAMS_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, DSA Parameters footer is missing"); } // Verify that the key starts with the correct header before passing it to parseOpenSslDsa if (OPENSSL_DSA_HEADER.equals(bReader.readLine()) == false) { throw new IOException("Malformed PEM file, DSA Key header is missing"); } return bReader; } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an plaintext private key encoded in * PKCS#8 * * @param bReader the {@link BufferedReader} containing the key file contents * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link PKCS8EncodedKeySpec} */ private static PrivateKey parsePKCS8(BufferedReader bReader) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line || PKCS8_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = Base64.getDecoder().decode(sb.toString()); String keyAlgo = getKeyAlgorithmIdentifier(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an EC private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link ECPrivateKeySpec} */ private static PrivateKey parseOpenSslEC(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (OPENSSL_EC_FOOTER.equals(line.trim())) { break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || OPENSSL_EC_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); KeyFactory keyFactory = KeyFactory.getInstance("EC"); ECPrivateKeySpec ecSpec = parseEcDer(keyBytes); return keyFactory.generatePrivate(ecSpec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an RSA private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link RSAPrivateCrtKeySpec} */ private static PrivateKey parsePKCS1Rsa(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (PKCS1_FOOTER.equals(line.trim())) { // Unencrypted break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || PKCS1_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); RSAPrivateCrtKeySpec spec = parseRsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(spec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an DSA private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link DSAPrivateKeySpec} */ private static PrivateKey parseOpenSslDsa(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (OPENSSL_DSA_FOOTER.equals(line.trim())) { // Unencrypted break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || OPENSSL_DSA_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); DSAPrivateKeySpec spec = parseDsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePrivate(spec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an encrypted private key encoded in * PKCS#8 * * @param bReader the {@link BufferedReader} containing the key file contents * @param keyPassword The password for the encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link PKCS8EncodedKeySpec} */ private static PrivateKey parsePKCS8Encrypted(BufferedReader bReader, char[] keyPassword) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_ENCRYPTED_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line || PKCS8_ENCRYPTED_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = Base64.getDecoder().decode(sb.toString()); EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(keyBytes); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(keyPassword)); Arrays.fill(keyPassword, '\u0000'); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters()); PKCS8EncodedKeySpec keySpec = encryptedPrivateKeyInfo.getKeySpec(cipher); String keyAlgo = getKeyAlgorithmIdentifier(keySpec.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(keySpec); } /** * Decrypts the password protected contents using the algorithm and IV that is specified in the PEM Headers of the file * * @param pemHeaders The Proc-Type and DEK-Info PEM headers that have been extracted from the key file * @param keyContents The key as a base64 encoded String * @param passwordSupplier A password supplier for the encrypted (password protected) key * @return the decrypted key bytes * @throws GeneralSecurityException if the key can't be decrypted * @throws IOException if the PEM headers are missing or malformed */ private static byte[] possiblyDecryptPKCS1Key(Map<String, String> pemHeaders, String keyContents, Supplier<char[]> passwordSupplier) throws GeneralSecurityException, IOException { byte[] keyBytes = Base64.getDecoder().decode(keyContents); String procType = pemHeaders.get("Proc-Type"); if ("4,ENCRYPTED".equals(procType)) { //We only handle PEM encryption String encryptionParameters = pemHeaders.get("DEK-Info"); if (null == encryptionParameters) { //malformed pem throw new IOException("Malformed PEM File, DEK-Info header is missing"); } char[] password = passwordSupplier.get(); if (password == null) { throw new IOException("cannot read encrypted key without a password"); } Cipher cipher = getCipherFromParameters(encryptionParameters, password); byte[] decryptedKeyBytes = cipher.doFinal(keyBytes); return decryptedKeyBytes; } return keyBytes; } /** * Creates a {@link Cipher} from the contents of the DEK-Info header of a PEM file. RFC 1421 indicates that supported algorithms are * defined in RFC 1423. RFC 1423 only defines DES-CBS and triple DES (EDE) in CBC mode. AES in CBC mode is also widely used though ( 3 * different variants of 128, 192, 256 bit keys ) * * @param dekHeaderValue The value of the the DEK-Info PEM header * @param password The password with which the key is encrypted * @return a cipher of the appropriate algorithm and parameters to be used for decryption * @throws GeneralSecurityException if the algorithm is not available in the used security provider, or if the key is inappropriate * for the cipher * @throws IOException if the DEK-Info PEM header is invalid */ private static Cipher getCipherFromParameters(String dekHeaderValue, char[] password) throws GeneralSecurityException, IOException { final String padding = "PKCS5Padding"; final SecretKey encryptionKey; final String[] valueTokens = dekHeaderValue.split(","); if (valueTokens.length != 2) { throw new IOException("Malformed PEM file, DEK-Info PEM header is invalid"); } final String algorithm = valueTokens[0]; final String ivString = valueTokens[1]; final byte[] iv; try { iv = hexStringToByteArray(ivString); } catch (IllegalArgumentException e) { throw new IOException("Malformed PEM file, DEK-Info IV is invalid", e); } if ("DES-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 8); encryptionKey = new SecretKeySpec(key, "DES"); } else if ("DES-EDE3-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, "DESede"); } else if ("AES-128-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 16); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-192-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-256-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 32); encryptionKey = new SecretKeySpec(key, "AES"); } else { throw new GeneralSecurityException("Private Key encrypted with unsupported algorithm [" + algorithm + "]"); } String transformation = encryptionKey.getAlgorithm() + "/" + "CBC" + "/" + padding; Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); return cipher; } /** * Performs key stretching in the same manner that OpenSSL does. This is basically a KDF * that uses n rounds of salted MD5 (as many times as needed to get the necessary number of key bytes) * <p> * https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_PrivateKey_traditional.html */ private static byte[] generateOpenSslKey(char[] password, byte[] salt, int keyLength) { byte[] passwordBytes = CharArrays.toUtf8Bytes(password); MessageDigest md5 = messageDigest("md5"); byte[] key = new byte[keyLength]; int copied = 0; int remaining; while (copied < keyLength) { remaining = keyLength - copied; md5.update(passwordBytes, 0, passwordBytes.length); md5.update(salt, 0, 8);// AES IV (salt) is longer but we only need 8 bytes byte[] tempDigest = md5.digest(); int bytesToCopy = (remaining > 16) ? 16 : remaining; // MD5 digests are 16 bytes System.arraycopy(tempDigest, 0, key, copied, bytesToCopy); copied += bytesToCopy; if (remaining == 0) { break; } md5.update(tempDigest, 0, 16); // use previous round digest as IV } Arrays.fill(passwordBytes, (byte) 0); return key; } /** * Converts a hexadecimal string to a byte array */ private static byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); if (len % 2 == 0) { byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { final int k = Character.digit(hexString.charAt(i), 16); final int l = Character.digit(hexString.charAt(i + 1), 16); if (k == -1 || l == -1) { throw new IllegalStateException("String [" + hexString + "] is not hexadecimal"); } data[i / 2] = (byte) ((k << 4) + l); } return data; } else { throw new IllegalStateException("Hexadecimal string [" + hexString + "] has odd length and cannot be converted to a byte array"); } } /** * Parses a DER encoded EC key to an {@link ECPrivateKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link ECPrivateKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static ECPrivateKeySpec parseEcDer(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // version String keyHex = parser.readAsn1Object().getString(); BigInteger privateKeyInt = new BigInteger(keyHex, 16); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); AlgorithmParameterSpec prime256v1ParamSpec = new ECGenParameterSpec("secp256r1"); keyPairGenerator.initialize(prime256v1ParamSpec); ECParameterSpec parameterSpec = ((ECKey) keyPairGenerator.generateKeyPair().getPrivate()).getParams(); return new ECPrivateKeySpec(privateKeyInt, parameterSpec); } /** * Parses a DER encoded RSA key to a {@link RSAPrivateCrtKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link RSAPrivateCrtKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static RSAPrivateCrtKeySpec parseRsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // (version) We don't need it but must read to get to modulus BigInteger modulus = parser.readAsn1Object().getInteger(); BigInteger publicExponent = parser.readAsn1Object().getInteger(); BigInteger privateExponent = parser.readAsn1Object().getInteger(); BigInteger prime1 = parser.readAsn1Object().getInteger(); BigInteger prime2 = parser.readAsn1Object().getInteger(); BigInteger exponent1 = parser.readAsn1Object().getInteger(); BigInteger exponent2 = parser.readAsn1Object().getInteger(); BigInteger coefficient = parser.readAsn1Object().getInteger(); return new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2, coefficient); } /** * Parses a DER encoded DSA key to a {@link DSAPrivateKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link DSAPrivateKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static DSAPrivateKeySpec parseDsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // (version) We don't need it but must read to get to p BigInteger p = parser.readAsn1Object().getInteger(); BigInteger q = parser.readAsn1Object().getInteger(); BigInteger g = parser.readAsn1Object().getInteger(); parser.readAsn1Object().getInteger(); // we don't need x BigInteger x = parser.readAsn1Object().getInteger(); return new DSAPrivateKeySpec(x, p, q, g); } /** * Parses a DER encoded private key and reads its algorithm identifier Object OID. * * @param keyBytes the private key raw bytes * @return A string identifier for the key algorithm (RSA, DSA, or EC) * @throws GeneralSecurityException if the algorithm oid that is parsed from ASN.1 is unknown * @throws IOException if the DER encoded key can't be parsed */ private static String getKeyAlgorithmIdentifier(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // version DerParser.Asn1Object algSequence = parser.readAsn1Object(); parser = algSequence.getParser(); String oidString = parser.readAsn1Object().getOid(); switch (oidString) { case "1.2.840.10040.4.1": return "DSA"; case "1.2.840.113549.1.1.1": return "RSA"; case "1.2.840.10045.2.1": return "EC"; } throw new GeneralSecurityException("Error parsing key algorithm identifier. Algorithm with OID [" + oidString + "] is not żsupported"); } static List<Certificate> readCertificates(Collection<Path> certPaths) throws CertificateException, IOException { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); List<Certificate> certificates = new ArrayList<>(certPaths.size()); for (Path path : certPaths) { try (InputStream input = Files.newInputStream(path)) { final Collection<? extends Certificate> parsed = certFactory.generateCertificates(input); if (parsed.isEmpty()) { throw new SslConfigException("failed to parse any certificates from [" + path.toAbsolutePath() + "]"); } certificates.addAll(parsed); } } return certificates; } private static MessageDigest messageDigest(String digestAlgorithm) { try { return MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new SslConfigException("unexpected exception creating MessageDigest instance for [" + digestAlgorithm + "]", e); } } }
apache-2.0
tsugiproject/tsugi
vendor/google/apiclient-services/src/Google/Service/RecommendationsAI/GoogleCloudRecommendationengineV1alphaRejoinCatalogResponse.php
998
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_RecommendationsAI_GoogleCloudRecommendationengineV1alphaRejoinCatalogResponse extends Google_Model { public $rejoinedUserEventsCount; public function setRejoinedUserEventsCount($rejoinedUserEventsCount) { $this->rejoinedUserEventsCount = $rejoinedUserEventsCount; } public function getRejoinedUserEventsCount() { return $this->rejoinedUserEventsCount; } }
apache-2.0
McLeodMoores/starling
projects/web/web-engine/prototype/modules/views/securities/og.views.securities.cds_index_definition.html
2955
<article> <header class="OG-header-generic"> <div class="OG-tools"></div> <h1>{{html name}}</h1> <div class="OG-js-header-links"></div> </header> <section> <div class="OG-details-content OG-js-details-panel"> <section class="og-js-identifiers"></section> <section> <table class="OG-table"> <col style="width: 40%" /> <col style="width: 60%" /> <thead> <tr> <th><span><em>${securityType.lang()}</em></span></th><th>&nbsp;</th> </tr> </thead> <tbody> <tr><td><span>Name</span></td><td>${name}</td></tr> <tr><td><span>Family</span></td><td>${family}</td></tr> <tr><td><span>Series</span></td><td>${series}</td></tr> <tr><td><span>Currency</span></td><td>${currency}</td></tr> <tr><td><span>Recovery Rate</span></td><td>${recovery}</td></tr> <tr> <td><span>Terms</span></td> <td>{{if terms}}{{each terms}}${this}&nbsp;&nbsp;&nbsp;{{/each}}{{/if}}</td> </tr> </tbody> </table> {{if components}} {{each components}} <table class="OG-table"> <col style="width: 40%" /> <col style="width: 60%" /> <tbody> <tr><td><span>Bond Scheme</span></td><td><span>${bond.scheme}</span></td></tr> <tr><td><span>Bond Value</span></td><td><span>${bond.value}</span></td></tr> <tr><td><span>Obligor Scheme</span></td><td><span>${obligor.scheme}</span></td></tr> <tr><td><span>Obligor Value</span></td><td><span>${obligor.value}</span></td></tr> <tr><td><span>Name</span></td><td><span>${name}</span></td></tr> <tr><td><span>Weight</span></td><td><span>${weight}</span></td></tr> </tbody> </table> {{/each}} {{/if}} </section> <section class="OG-timeseries-container"></section> <section> <table class="OG-table"> <col style="width: 40%" /> <col style="width: 60%" /> <thead> <tr><th colspan="2"><span><em>Attributes</em></span></th></tr> <tr> <th><div><em>Name</em></div></th> <th><div><em>Value</em></div></th> </tr> </thead> <tbody> {{if attributes}} {{each(attribute_index, attribute_value) attributes}} <tr> <td><span>${attribute_index}</span></td> <td><span>${attribute_value}</span></td> </tr> {{/each}} {{else}} <tr> <td colspan="2"><span>(no values)</span></td> </tr> {{/if}} </tbody> </table> </section> </div> </section> </article>
apache-2.0
apurtell/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/AclTransformation.java
21791
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import static org.apache.hadoop.fs.permission.AclEntryScope.*; import static org.apache.hadoop.fs.permission.AclEntryType.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.AclEntryType; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.ScopedAclEntries; import org.apache.hadoop.hdfs.protocol.AclException; import org.apache.hadoop.util.Lists; import org.apache.hadoop.thirdparty.com.google.common.collect.ComparisonChain; import org.apache.hadoop.thirdparty.com.google.common.collect.Maps; import org.apache.hadoop.thirdparty.com.google.common.collect.Ordering; /** * AclTransformation defines the operations that can modify an ACL. All ACL * modifications take as input an existing ACL and apply logic to add new * entries, modify existing entries or remove old entries. Some operations also * accept an ACL spec: a list of entries that further describes the requested * change. Different operations interpret the ACL spec differently. In the * case of adding an ACL to an inode that previously did not have one, the * existing ACL can be a "minimal ACL" containing exactly 3 entries for owner, * group and other, all derived from the {@link FsPermission} bits. * * The algorithms implemented here require sorted lists of ACL entries. For any * existing ACL, it is assumed that the entries are sorted. This is because all * ACL creation and modification is intended to go through these methods, and * they all guarantee correct sort order in their outputs. However, an ACL spec * is considered untrusted user input, so all operations pre-sort the ACL spec as * the first step. */ @InterfaceAudience.Private final class AclTransformation { private static final int MAX_ENTRIES = 32; /** * Filters (discards) any existing ACL entries that have the same scope, type * and name of any entry in the ACL spec. If necessary, recalculates the mask * entries. If necessary, default entries may be inferred by copying the * permissions of the corresponding access entries. It is invalid to request * removal of the mask entry from an ACL that would otherwise require a mask * entry, due to existing named entries or an unnamed group entry. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec describing entries to filter * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { if (aclSpec.containsKey(existingEntry)) { scopeDirty.add(existingEntry.getScope()); if (existingEntry.getType() == MASK) { maskDirty.add(existingEntry.getScope()); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * Filters (discards) any existing default ACL entries. The new ACL retains * only the access ACL entries. * * @param existingAcl List<AclEntry> existing ACL * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> filterDefaultAclEntries( List<AclEntry> existingAcl) throws AclException { ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); for (AclEntry existingEntry: existingAcl) { if (existingEntry.getScope() == DEFAULT) { // Default entries sort after access entries, so we can exit early. break; } aclBuilder.add(existingEntry); } return buildAndValidateAcl(aclBuilder); } /** * Merges the entries of the ACL spec into the existing ACL. If necessary, * recalculates the mask entries. If necessary, default entries may be * inferred by copying the permissions of the corresponding access entries. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec containing entries to merge * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { AclEntry aclSpecEntry = aclSpec.findByKey(existingEntry); if (aclSpecEntry != null) { foundAclSpecEntries.add(aclSpecEntry); scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } // ACL spec entries that were not replacements are new additions. for (AclEntry newEntry: aclSpec) { if (Collections.binarySearch(foundAclSpecEntries, newEntry, ACL_ENTRY_COMPARATOR) < 0) { scopeDirty.add(newEntry.getScope()); if (newEntry.getType() == MASK) { providedMask.put(newEntry.getScope(), newEntry); maskDirty.add(newEntry.getScope()); } else { aclBuilder.add(newEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * Completely replaces the ACL with the entries of the ACL spec. If * necessary, recalculates the mask entries. If necessary, default entries * are inferred by copying the permissions of the corresponding access * entries. Replacement occurs separately for each of the access ACL and the * default ACL. If the ACL spec contains only access entries, then the * existing default entries are retained. If the ACL spec contains only * default entries, then the existing access entries are retained. If the ACL * spec contains both access and default entries, then both are replaced. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec containing replacement entries * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for each scope: access and default. EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry aclSpecEntry: aclSpec) { scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } // Copy existing entries if the scope was not replaced. for (AclEntry existingEntry: existingAcl) { if (!scopeDirty.contains(existingEntry.getScope())) { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * There is no reason to instantiate this class. */ private AclTransformation() { } /** * Comparator that enforces required ordering for entries within an ACL: * -owner entry (unnamed user) * -all named user entries (internal ordering undefined) * -owning group entry (unnamed group) * -all named group entries (internal ordering undefined) * -mask entry * -other entry * All access ACL entries sort ahead of all default ACL entries. */ static final Comparator<AclEntry> ACL_ENTRY_COMPARATOR = new Comparator<AclEntry>() { @Override public int compare(AclEntry entry1, AclEntry entry2) { return ComparisonChain.start() .compare(entry1.getScope(), entry2.getScope(), Ordering.explicit(ACCESS, DEFAULT)) .compare(entry1.getType(), entry2.getType(), Ordering.explicit(USER, GROUP, MASK, OTHER)) .compare(entry1.getName(), entry2.getName(), Ordering.natural().nullsFirst()) .result(); } }; /** * Builds the final list of ACL entries to return by trimming, sorting and * validating the ACL entries that have been added. * * @param aclBuilder ArrayList<AclEntry> containing entries to build * @return List<AclEntry> unmodifiable, sorted list of ACL entries * @throws AclException if validation fails */ private static List<AclEntry> buildAndValidateAcl( ArrayList<AclEntry> aclBuilder) throws AclException { aclBuilder.trimToSize(); Collections.sort(aclBuilder, ACL_ENTRY_COMPARATOR); // Full iteration to check for duplicates and invalid named entries. AclEntry prevEntry = null; for (AclEntry entry: aclBuilder) { if (prevEntry != null && ACL_ENTRY_COMPARATOR.compare(prevEntry, entry) == 0) { throw new AclException( "Invalid ACL: multiple entries with same scope, type and name."); } if (entry.getName() != null && (entry.getType() == MASK || entry.getType() == OTHER)) { throw new AclException( "Invalid ACL: this entry type must not have a name: " + entry + "."); } prevEntry = entry; } ScopedAclEntries scopedEntries = new ScopedAclEntries(aclBuilder); checkMaxEntries(scopedEntries); // Search for the required base access entries. If there is a default ACL, // then do the same check on the default entries. for (AclEntryType type: EnumSet.of(USER, GROUP, OTHER)) { AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS) .setType(type).build(); if (Collections.binarySearch(scopedEntries.getAccessEntries(), accessEntryKey, ACL_ENTRY_COMPARATOR) < 0) { throw new AclException( "Invalid ACL: the user, group and other entries are required."); } if (!scopedEntries.getDefaultEntries().isEmpty()) { AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT) .setType(type).build(); if (Collections.binarySearch(scopedEntries.getDefaultEntries(), defaultEntryKey, ACL_ENTRY_COMPARATOR) < 0) { throw new AclException( "Invalid default ACL: the user, group and other entries are required."); } } } return Collections.unmodifiableList(aclBuilder); } // Check the max entries separately on access and default entries // HDFS-7582 private static void checkMaxEntries(ScopedAclEntries scopedEntries) throws AclException { List<AclEntry> accessEntries = scopedEntries.getAccessEntries(); List<AclEntry> defaultEntries = scopedEntries.getDefaultEntries(); if (accessEntries.size() > MAX_ENTRIES) { throw new AclException("Invalid ACL: ACL has " + accessEntries.size() + " access entries, which exceeds maximum of " + MAX_ENTRIES + "."); } if (defaultEntries.size() > MAX_ENTRIES) { throw new AclException("Invalid ACL: ACL has " + defaultEntries.size() + " default entries, which exceeds maximum of " + MAX_ENTRIES + "."); } } /** * Calculates mask entries required for the ACL. Mask calculation is performed * separately for each scope: access and default. This method is responsible * for handling the following cases of mask calculation: * 1. Throws an exception if the caller attempts to remove the mask entry of an * existing ACL that requires it. If the ACL has any named entries, then a * mask entry is required. * 2. If the caller supplied a mask in the ACL spec, use it. * 3. If the caller did not supply a mask, but there are ACL entry changes in * this scope, then automatically calculate a new mask. The permissions of * the new mask are the union of the permissions on the group entry and all * named entries. * * @param aclBuilder ArrayList<AclEntry> containing entries to build * @param providedMask EnumMap<AclEntryScope, AclEntry> mapping each scope to * the mask entry that was provided for that scope (if provided) * @param maskDirty EnumSet<AclEntryScope> which contains a scope if the mask * entry is dirty (added or deleted) in that scope * @param scopeDirty EnumSet<AclEntryScope> which contains a scope if any entry * is dirty (added or deleted) in that scope * @throws AclException if validation fails */ private static void calculateMasks(List<AclEntry> aclBuilder, EnumMap<AclEntryScope, AclEntry> providedMask, EnumSet<AclEntryScope> maskDirty, EnumSet<AclEntryScope> scopeDirty) throws AclException { EnumSet<AclEntryScope> scopeFound = EnumSet.noneOf(AclEntryScope.class); EnumMap<AclEntryScope, FsAction> unionPerms = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskNeeded = EnumSet.noneOf(AclEntryScope.class); // Determine which scopes are present, which scopes need a mask, and the // union of group class permissions in each scope. for (AclEntry entry: aclBuilder) { scopeFound.add(entry.getScope()); if (entry.getType() == GROUP || entry.getName() != null) { FsAction scopeUnionPerms = unionPerms.get(entry.getScope()); if (scopeUnionPerms == null) { scopeUnionPerms = FsAction.NONE; } unionPerms.put(entry.getScope(), scopeUnionPerms.or(entry.getPermission())); } if (entry.getName() != null) { maskNeeded.add(entry.getScope()); } } // Add mask entry if needed in each scope. for (AclEntryScope scope: scopeFound) { if (!providedMask.containsKey(scope) && maskNeeded.contains(scope) && maskDirty.contains(scope)) { // Caller explicitly removed mask entry, but it's required. throw new AclException( "Invalid ACL: mask is required and cannot be deleted."); } else if (providedMask.containsKey(scope) && (!scopeDirty.contains(scope) || maskDirty.contains(scope))) { // Caller explicitly provided new mask, or we are preserving the existing // mask in an unchanged scope. aclBuilder.add(providedMask.get(scope)); } else if (maskNeeded.contains(scope) || providedMask.containsKey(scope)) { // Otherwise, if there are maskable entries present, or the ACL // previously had a mask, then recalculate a mask automatically. aclBuilder.add(new AclEntry.Builder() .setScope(scope) .setType(MASK) .setPermission(unionPerms.get(scope)) .build()); } } } /** * Adds unspecified default entries by copying permissions from the * corresponding access entries. * * @param aclBuilder ArrayList<AclEntry> containing entries to build */ private static void copyDefaultsIfNeeded(List<AclEntry> aclBuilder) { Collections.sort(aclBuilder, ACL_ENTRY_COMPARATOR); ScopedAclEntries scopedEntries = new ScopedAclEntries(aclBuilder); if (!scopedEntries.getDefaultEntries().isEmpty()) { List<AclEntry> accessEntries = scopedEntries.getAccessEntries(); List<AclEntry> defaultEntries = scopedEntries.getDefaultEntries(); List<AclEntry> copiedEntries = Lists.newArrayListWithCapacity(3); for (AclEntryType type: EnumSet.of(USER, GROUP, OTHER)) { AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT) .setType(type).build(); int defaultEntryIndex = Collections.binarySearch(defaultEntries, defaultEntryKey, ACL_ENTRY_COMPARATOR); if (defaultEntryIndex < 0) { AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS) .setType(type).build(); int accessEntryIndex = Collections.binarySearch(accessEntries, accessEntryKey, ACL_ENTRY_COMPARATOR); if (accessEntryIndex >= 0) { copiedEntries.add(new AclEntry.Builder() .setScope(DEFAULT) .setType(type) .setPermission(accessEntries.get(accessEntryIndex).getPermission()) .build()); } } } // Add all copied entries when done to prevent potential issues with binary // search on a modified aclBulider during the main loop. aclBuilder.addAll(copiedEntries); } } /** * An ACL spec that has been pre-validated and sorted. */ private static final class ValidatedAclSpec implements Iterable<AclEntry> { private final List<AclEntry> aclSpec; /** * Creates a ValidatedAclSpec by pre-validating and sorting the given ACL * entries. Pre-validation checks that it does not exceed the maximum * entries. This check is performed before modifying the ACL, and it's * actually insufficient for enforcing the maximum number of entries. * Transformation logic can create additional entries automatically,such as * the mask and some of the default entries, so we also need additional * checks during transformation. The up-front check is still valuable here * so that we don't run a lot of expensive transformation logic while * holding the namesystem lock for an attacker who intentionally sent a huge * ACL spec. * * @param aclSpec List<AclEntry> containing unvalidated input ACL spec * @throws AclException if validation fails */ public ValidatedAclSpec(List<AclEntry> aclSpec) throws AclException { Collections.sort(aclSpec, ACL_ENTRY_COMPARATOR); checkMaxEntries(new ScopedAclEntries(aclSpec)); this.aclSpec = aclSpec; } /** * Returns true if this contains an entry matching the given key. An ACL * entry's key consists of scope, type and name (but not permission). * * @param key AclEntry search key * @return boolean true if found */ public boolean containsKey(AclEntry key) { return Collections.binarySearch(aclSpec, key, ACL_ENTRY_COMPARATOR) >= 0; } /** * Returns the entry matching the given key or null if not found. An ACL * entry's key consists of scope, type and name (but not permission). * * @param key AclEntry search key * @return AclEntry entry matching the given key or null if not found */ public AclEntry findByKey(AclEntry key) { int index = Collections.binarySearch(aclSpec, key, ACL_ENTRY_COMPARATOR); if (index >= 0) { return aclSpec.get(index); } return null; } @Override public Iterator<AclEntry> iterator() { return aclSpec.iterator(); } } }
apache-2.0
0359xiaodong/PagedHeadListView
library/src/main/java/com/jorgecastilloprz/pagedheadlistview/pagetransformers/DepthPageTransformer.java
1412
package com.jorgecastilloprz.pagedheadlistview.pagetransformers; import android.support.v4.view.ViewPager; import android.view.View; /** * Created by jorge on 10/08/14. */ public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0); } else if (position <= 0) { // [-1,0] // Use the default slide transition when moving to the left page view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); } else if (position <= 1) { // (0,1] // Fade the page out. view.setAlpha(1 - position); // Counteract the default slide transition view.setTranslationX(pageWidth * -position); // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0); } } }
apache-2.0
daedric/buck
src/com/facebook/buck/json/BuildFileParseException.java
1826
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.json; import com.facebook.buck.util.ExceptionWithHumanReadableMessage; import java.io.IOException; import java.nio.file.Path; /** * Thrown if we encounter an unexpected, fatal condition while interacting with the * build file parser. */ @SuppressWarnings("serial") public class BuildFileParseException extends Exception implements ExceptionWithHumanReadableMessage { private BuildFileParseException(String message) { super(message); } static BuildFileParseException createForUnknownParseError(String message) { return new BuildFileParseException(message); } private static String formatMessageWithCause(String message, IOException cause) { if (cause != null && cause.getMessage() != null) { return message + ":\n" + cause.getMessage(); } else { return message; } } static BuildFileParseException createForBuildFileParseError(Path buildFile, IOException cause) { String message = String.format("Parse error for build file %s", buildFile); return new BuildFileParseException(formatMessageWithCause(message, cause)); } @Override public String getHumanReadableErrorMessage() { return getMessage(); } }
apache-2.0
terrorform/pool-resource
vendor/gopkg.in/src-d/go-git.v4/plumbing/protocol/packp/srvresp.go
2799
package packp import ( "bufio" "bytes" "errors" "fmt" "io" "gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing/format/pktline" ) const ackLineLen = 44 // ServerResponse object acknowledgement from upload-pack service type ServerResponse struct { ACKs []plumbing.Hash } // Decode decodes the response into the struct, isMultiACK should be true, if // the request was done with multi_ack or multi_ack_detailed capabilities. func (r *ServerResponse) Decode(reader *bufio.Reader, isMultiACK bool) error { // TODO: implement support for multi_ack or multi_ack_detailed responses if isMultiACK { return errors.New("multi_ack and multi_ack_detailed are not supported") } s := pktline.NewScanner(reader) for s.Scan() { line := s.Bytes() if err := r.decodeLine(line); err != nil { return err } // we need to detect when the end of a response header and the begining // of a packfile header happend, some requests to the git daemon // produces a duplicate ACK header even when multi_ack is not supported. stop, err := r.stopReading(reader) if err != nil { return err } if stop { break } } return s.Err() } // stopReading detects when a valid command such as ACK or NAK is found to be // read in the buffer without moving the read pointer. func (r *ServerResponse) stopReading(reader *bufio.Reader) (bool, error) { ahead, err := reader.Peek(7) if err == io.EOF { return true, nil } if err != nil { return false, err } if len(ahead) > 4 && r.isValidCommand(ahead[0:3]) { return false, nil } if len(ahead) == 7 && r.isValidCommand(ahead[4:]) { return false, nil } return true, nil } func (r *ServerResponse) isValidCommand(b []byte) bool { commands := [][]byte{ack, nak} for _, c := range commands { if bytes.Compare(b, c) == 0 { return true } } return false } func (r *ServerResponse) decodeLine(line []byte) error { if len(line) == 0 { return fmt.Errorf("unexpected flush") } if bytes.Compare(line[0:3], ack) == 0 { return r.decodeACKLine(line) } if bytes.Compare(line[0:3], nak) == 0 { return nil } return fmt.Errorf("unexpected content %q", string(line)) } func (r *ServerResponse) decodeACKLine(line []byte) error { if len(line) < ackLineLen { return fmt.Errorf("malformed ACK %q", line) } sp := bytes.Index(line, []byte(" ")) h := plumbing.NewHash(string(line[sp+1 : sp+41])) r.ACKs = append(r.ACKs, h) return nil } // Encode encodes the ServerResponse into a writer. func (r *ServerResponse) Encode(w io.Writer) error { if len(r.ACKs) > 1 { return errors.New("multi_ack and multi_ack_detailed are not supported") } e := pktline.NewEncoder(w) if len(r.ACKs) == 0 { return e.Encodef("%s\n", nak) } return e.Encodef("%s %s\n", ack, r.ACKs[0].String()) }
apache-2.0
yjaradin/mozart2
vm/generator/main/interfaces.cc
5779
// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "generator.hh" #include <sstream> using namespace clang; struct InterfaceDef { InterfaceDef() { name = ""; implems = 0; autoWait = true; autoReflectiveCalls = true; } void makeOutput(const SpecDecl* ND, llvm::raw_fd_ostream& to); std::string name; const TemplateSpecializationType* implems; bool autoWait; bool autoReflectiveCalls; }; void handleInterface(const std::string& outputDir, const SpecDecl* ND) { const std::string name = getTypeParamAsString(ND); InterfaceDef definition; definition.name = name; // For every marker, i.e. base class for (auto iter = ND->bases_begin(), e = ND->bases_end(); iter != e; ++iter) { CXXRecordDecl* marker = iter->getType()->getAsCXXRecordDecl(); std::string markerLabel = marker->getNameAsString(); if (markerLabel == "ImplementedBy") { definition.implems = dyn_cast<TemplateSpecializationType>(iter->getType().getTypePtr()); } else if (markerLabel == "NoAutoWait") { definition.autoWait = false; } else if (markerLabel == "NoAutoReflectiveCalls") { definition.autoReflectiveCalls = false; } else {} } // Write output withFileOutputStream(outputDir + name + "-interf.hh", [&] (ostream& to) { definition.makeOutput(ND, to); }); } void InterfaceDef::makeOutput(const SpecDecl* ND, llvm::raw_fd_ostream& to) { to << "class "<< name << " {\n"; to << "public:\n"; to << " " << name << "(RichNode self) : _self(self) {}\n"; to << " " << name << "(UnstableNode& self) : _self(self) {}\n"; to << " " << name << "(StableNode& self) : _self(self) {}\n"; for (auto iter = ND->decls_begin(), e = ND->decls_end(); iter != e; ++iter) { const Decl* decl = *iter; if (decl->isImplicit()) continue; if (!decl->isFunctionOrFunctionTemplate()) continue; if (decl->getAccess() != AS_public) continue; const FunctionDecl* function; if ((function = dyn_cast<FunctionDecl>(decl))) { // Do nothing } else if (const FunctionTemplateDecl* funTemplate = dyn_cast<FunctionTemplateDecl>(decl)) { function = funTemplate->getTemplatedDecl(); TemplateParameterList* params = funTemplate->getTemplateParameters(); to << "\n "; printTemplateParameters(to, params); } if (!function->isCXXInstanceMember()) continue; std::string funName, resultType, formals, actuals, reflectActuals; parseFunction(function, funName, resultType, formals, actuals, reflectActuals, true); // Declaration of the procedure to << "\n " << resultType << " " << funName << "(" << formals << ") {\n "; // For every implementation that implements this interface (ImplementedBy) for (int i = 0; i < (int) implems->getNumArgs(); ++i) { std::string imp = implems->getArg(i).getAsType()->getAsCXXRecordDecl()->getNameAsString(); to << "if (_self.is<" << imp << ">()) {\n"; to << " return _self.as<" << imp << ">()." << funName << "(" << actuals << ");\n"; to << " } else "; } // Auto-wait handling if (autoWait) { to << "if (_self.isTransient()) {\n"; to << " waitFor(vm, _self);\n"; to << " throw std::exception(); // not reachable\n"; to << " } else "; } to << "{\n"; // Auto-reflective calls handling if (autoReflectiveCalls) { to << " if (_self.is< ::mozart::ReflectiveEntity>()) {\n"; if (resultType != "void") to << " " << resultType << " _result;\n"; to << " if (_self.as< ::mozart::ReflectiveEntity>()." << "reflectiveCall(vm, \"$intf$::" << name << "::" << funName << "\", \"" << funName << "\""; if (!reflectActuals.empty()) to << ", " << reflectActuals; if (resultType != "void") to << ", ::mozart::ozcalls::out(_result)"; to << "))\n"; if (resultType != "void") to << " return _result;\n"; else to << " return;\n"; to << " }\n"; } // Default behavior to << " return Interface<" << name << ">()." << funName << "(_self"; if (!actuals.empty()) to << ", " << actuals; to << ");\n"; to << " }\n"; to << " }\n"; } to << "protected:\n"; to << " RichNode _self;\n"; to << "};\n\n"; }
bsd-2-clause
jlord/git-it-electron
assets/PortableGit/mingw32/share/doc/git-doc/git-diff-tree.html
96907
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 1.5.2"> <title>git-diff-tree(1)</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400"> <style> /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ /* Remove the comments around the @import statement below when using this as a custom stylesheet */ /*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400";*/ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block} audio,canvas,video{display:inline-block} audio:not([controls]){display:none;height:0} [hidden],template{display:none} script{display:none!important} html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%} body{margin:0} a{background:transparent} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} abbr[title]{border-bottom:1px dotted} b,strong{font-weight:bold} dfn{font-style:italic} hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0} input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box} input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} #map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none!important} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} .antialiased,body{-webkit-font-smoothing:antialiased} img{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:none} p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em} ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit} ul.square{list-style-type:square} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ul.no-bullet{list-style:none} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help} abbr{text-transform:none} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)} blockquote cite:before{content:"\2014 \0020"} blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}}table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede} table thead,table tfoot{background:#f7f8f7;font-weight:bold} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table} .clearfix:after,.float-group:after{clear:both} *:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed} .keyseq{color:rgba(51,51,51,.8)} kbd{display:inline-block;color:rgba(0,0,0,.8);font-size:.75em;line-height:1.4;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:-.15em .15em 0 .15em;padding:.2em .6em .2em .5em;vertical-align:middle;white-space:nowrap} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menu{color:rgba(0,0,0,.8)} b.button:before,b.button:after{position:relative;top:-1px;font-weight:400} b.button:before{content:"[";padding:0 3px 0 2px} b.button:after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table} #header:after,#content:after,#footnotes:after,#footer:after{clear:both} #content{margin-top:1.25em} #content:before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8} #header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px} #header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span:before{content:"\00a0\2013\00a0"} #header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark:before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber:after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #efefed;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media only screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} #toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}}#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:rgba(255,255,255,.8);line-height:1.44} .sect1{padding-bottom:.625em} @media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}.sect1+.sect1{border-top:1px solid #efefed} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} .audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0} .paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)} table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px} .exampleblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child{margin-bottom:0} .sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} .sidebarblock>:first-child{margin-top:0} .sidebarblock>:last-child{margin-bottom:0} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8} .sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1} .literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em} .literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal} @media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .listingblock>.content{position:relative} .listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999} .listingblock:hover code[data-lang]:before{display:block} .listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999} .listingblock.terminal pre .command:not([data-prompt]):before{content:"$"} table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0} table.pyhltable td.code{padding-left:.75em;padding-right:0} pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8} pre.pygments .lineno{display:inline-block;margin-right:.25em} table.pyhltable .linenodiv{background:none!important;padding-right:0!important} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right} .quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)} .quoteblock .quoteblock blockquote{padding:0 0 0 .75em} .quoteblock .quoteblock blockquote:before{display:none} .verseblock{margin:0 1em 1.25em 1em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.05em;color:rgba(0,0,0,.6)} .quoteblock.abstract{margin:0 0 1.25em 0;display:block} .quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0} .quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none} table.tableblock{max-width:100%;border-collapse:separate} table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0} table.spread{width:100%} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0} table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0} table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0} table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0} table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0} table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0} table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0} table.frame-all{border-width:1px} table.frame-sides{border-width:0 1px} table.frame-topbot{border-width:1px 0} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} td>div.verse{white-space:pre} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none} ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em} ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em} ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px} ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden} ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block} ul.inline>li>*{display:block} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1{padding-right:.75em;font-weight:bold} td.hdlist1,td.hdlist2{vertical-align:top} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist>table tr>td:first-of-type{padding:0 .75em;line-height:1} .colist>table tr>td:last-of-type{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd} .imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0} .imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none} span.footnote,span.footnoteref{vertical-align:super;font-size:.875em} span.footnote a,span.footnoteref a{text-decoration:none} span.footnote a:active,span.footnoteref a:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0} #footnotes .footnote{padding:0 .375em;line-height:1.3;font-size:.875em;margin-left:1.2em;text-indent:-1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} .gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0} .gist .file-data>table td.line-data{width:99%} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background-color:#00fafa} .black{color:#000} .black-background{background-color:#000} .blue{color:#0000bf} .blue-background{background-color:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background-color:#fa00fa} .gray{color:#606060} .gray-background{background-color:#7d7d7d} .green{color:#006000} .green-background{background-color:#007d00} .lime{color:#00bf00} .lime-background{background-color:#00fa00} .maroon{color:#600000} .maroon-background{background-color:#7d0000} .navy{color:#000060} .navy-background{background-color:#00007d} .olive{color:#606000} .olive-background{background-color:#7d7d00} .purple{color:#600060} .purple-background{background-color:#7d007d} .red{color:#bf0000} .red-background{background-color:#fa0000} .silver{color:#909090} .silver-background{background-color:#bcbcbc} .teal{color:#006060} .teal-background{background-color:#007d7d} .white{color:#bfbfbf} .white-background{background-color:#fafafa} .yellow{color:#bfbf00} .yellow-background{background-color:#fafa00} span.icon>.fa{cursor:default} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]:after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} h1,h2{letter-spacing:-.01em} dt,th.tableblock,td.content{text-rendering:optimizeLegibility} p,td.content{letter-spacing:-.01em} p strong,td.content strong{letter-spacing:-.005em} p,blockquote,dt,td.content{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @media print{@page{margin:1.25cm .75cm} *{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]:after{content:" (" attr(title) ")"} pre,blockquote,tr,img{page-break-inside:avoid} thead{display:table-header-group} img{max-width:100%!important} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important} .sect1{padding-bottom:0!important} .sect1+.sect1{border:0!important} #header>h1:first-child{margin-top:1.25rem} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span:before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]:before{display:block} #footer{background:none!important;padding:0 .9375em} #footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} </style> </head> <body class="manpage"> <div id="header"> <h1>git-diff-tree(1) Manual Page</h1> <h2>NAME</h2> <div class="sectionbody"> <p>git-diff-tree - Compares the content and mode of blobs found via two tree objects</p> </div> </div> <div id="content"> <div class="sect1"> <h2 id="_synopsis">SYNOPSIS</h2> <div class="sectionbody"> <div class="verseblock"> <pre class="content"><em>git diff-tree</em> [--stdin] [-m] [-s] [-v] [--no-commit-id] [--pretty] [-t] [-r] [-c | --cc] [--root] [&lt;common diff options&gt;] &lt;tree-ish&gt; [&lt;tree-ish&gt;] [&lt;path&gt;&#8230;&#8203;]</pre> </div> </div> </div> <div class="sect1"> <h2 id="_description">DESCRIPTION</h2> <div class="sectionbody"> <div class="paragraph"> <p>Compares the content and mode of the blobs found via two tree objects.</p> </div> <div class="paragraph"> <p>If there is only one &lt;tree-ish&gt; given, the commit is compared with its parents (see --stdin below).</p> </div> <div class="paragraph"> <p>Note that <em>git diff-tree</em> can use the tree encapsulated in a commit object.</p> </div> </div> </div> <div class="sect1"> <h2 id="_options">OPTIONS</h2> <div class="sectionbody"> <div class="dlist"> <dl> <dt class="hdlist1">-p</dt> <dt class="hdlist1">-u</dt> <dt class="hdlist1">--patch</dt> <dd> <p>Generate patch (see section on generating patches).</p> </dd> <dt class="hdlist1">-s</dt> <dt class="hdlist1">--no-patch</dt> <dd> <p>Suppress diff output. Useful for commands like <code>git show</code> that show the patch by default, or to cancel the effect of <code>--patch</code>.</p> </dd> <dt class="hdlist1">-U&lt;n&gt;</dt> <dt class="hdlist1">--unified=&lt;n&gt;</dt> <dd> <p>Generate diffs with &lt;n&gt; lines of context instead of the usual three. Implies <code>-p</code>.</p> </dd> <dt class="hdlist1">--raw</dt> <dd> <p>Generate the diff in raw format. This is the default.</p> </dd> <dt class="hdlist1">--patch-with-raw</dt> <dd> <p>Synonym for <code>-p --raw</code>.</p> </dd> <dt class="hdlist1">--minimal</dt> <dd> <p>Spend extra time to make sure the smallest possible diff is produced.</p> </dd> <dt class="hdlist1">--patience</dt> <dd> <p>Generate a diff using the "patience diff" algorithm.</p> </dd> <dt class="hdlist1">--histogram</dt> <dd> <p>Generate a diff using the "histogram diff" algorithm.</p> </dd> <dt class="hdlist1">--diff-algorithm={patience|minimal|histogram|myers}</dt> <dd> <p>Choose a diff algorithm. The variants are as follows:</p> <div class="openblock"> <div class="content"> <div class="dlist"> <dl> <dt class="hdlist1"><code>default</code>, <code>myers</code></dt> <dd> <p>The basic greedy diff algorithm. Currently, this is the default.</p> </dd> <dt class="hdlist1"><code>minimal</code></dt> <dd> <p>Spend extra time to make sure the smallest possible diff is produced.</p> </dd> <dt class="hdlist1"><code>patience</code></dt> <dd> <p>Use "patience diff" algorithm when generating patches.</p> </dd> <dt class="hdlist1"><code>histogram</code></dt> <dd> <p>This algorithm extends the patience algorithm to "support low-occurrence common elements".</p> </dd> </dl> </div> </div> </div> <div class="paragraph"> <p>For instance, if you configured diff.algorithm variable to a non-default value and want to use the default one, then you have to use <code>--diff-algorithm=default</code> option.</p> </div> </dd> <dt class="hdlist1">--stat[=&lt;width&gt;[,&lt;name-width&gt;[,&lt;count&gt;]]]</dt> <dd> <p>Generate a diffstat. By default, as much space as necessary will be used for the filename part, and the rest for the graph part. Maximum width defaults to terminal width, or 80 columns if not connected to a terminal, and can be overridden by <code>&lt;width&gt;</code>. The width of the filename part can be limited by giving another width <code>&lt;name-width&gt;</code> after a comma. The width of the graph part can be limited by using <code>--stat-graph-width=&lt;width&gt;</code> (affects all commands generating a stat graph) or by setting <code>diff.statGraphWidth=&lt;width&gt;</code> (does not affect <code>git format-patch</code>). By giving a third parameter <code>&lt;count&gt;</code>, you can limit the output to the first <code>&lt;count&gt;</code> lines, followed by <code>...</code> if there are more.</p> <div class="paragraph"> <p>These parameters can also be set individually with <code>--stat-width=&lt;width&gt;</code>, <code>--stat-name-width=&lt;name-width&gt;</code> and <code>--stat-count=&lt;count&gt;</code>.</p> </div> </dd> <dt class="hdlist1">--numstat</dt> <dd> <p>Similar to <code>--stat</code>, but shows number of added and deleted lines in decimal notation and pathname without abbreviation, to make it more machine friendly. For binary files, outputs two <code>-</code> instead of saying <code>0 0</code>.</p> </dd> <dt class="hdlist1">--shortstat</dt> <dd> <p>Output only the last line of the <code>--stat</code> format containing total number of modified files, as well as number of added and deleted lines.</p> </dd> <dt class="hdlist1">--dirstat[=&lt;param1,param2,&#8230;&#8203;&gt;]</dt> <dd> <p>Output the distribution of relative amount of changes for each sub-directory. The behavior of <code>--dirstat</code> can be customized by passing it a comma separated list of parameters. The defaults are controlled by the <code>diff.dirstat</code> configuration variable (see linkgit:git-config[1]). The following parameters are available:</p> <div class="openblock"> <div class="content"> <div class="dlist"> <dl> <dt class="hdlist1"><code>changes</code></dt> <dd> <p>Compute the dirstat numbers by counting the lines that have been removed from the source, or added to the destination. This ignores the amount of pure code movements within a file. In other words, rearranging lines in a file is not counted as much as other changes. This is the default behavior when no parameter is given.</p> </dd> <dt class="hdlist1"><code>lines</code></dt> <dd> <p>Compute the dirstat numbers by doing the regular line-based diff analysis, and summing the removed/added line counts. (For binary files, count 64-byte chunks instead, since binary files have no natural concept of lines). This is a more expensive <code>--dirstat</code> behavior than the <code>changes</code> behavior, but it does count rearranged lines within a file as much as other changes. The resulting output is consistent with what you get from the other <code>--*stat</code> options.</p> </dd> <dt class="hdlist1"><code>files</code></dt> <dd> <p>Compute the dirstat numbers by counting the number of files changed. Each changed file counts equally in the dirstat analysis. This is the computationally cheapest <code>--dirstat</code> behavior, since it does not have to look at the file contents at all.</p> </dd> <dt class="hdlist1"><code>cumulative</code></dt> <dd> <p>Count changes in a child directory for the parent directory as well. Note that when using <code>cumulative</code>, the sum of the percentages reported may exceed 100%. The default (non-cumulative) behavior can be specified with the <code>noncumulative</code> parameter.</p> </dd> <dt class="hdlist1">&lt;limit&gt;</dt> <dd> <p>An integer parameter specifies a cut-off percent (3% by default). Directories contributing less than this percentage of the changes are not shown in the output.</p> </dd> </dl> </div> </div> </div> <div class="paragraph"> <p>Example: The following will count changed files, while ignoring directories with less than 10% of the total amount of changed files, and accumulating child directory counts in the parent directories: <code>--dirstat=files,10,cumulative</code>.</p> </div> </dd> <dt class="hdlist1">--summary</dt> <dd> <p>Output a condensed summary of extended header information such as creations, renames and mode changes.</p> </dd> <dt class="hdlist1">--patch-with-stat</dt> <dd> <p>Synonym for <code>-p --stat</code>.</p> </dd> <dt class="hdlist1">-z</dt> <dd> <p>When <code>--raw</code>, <code>--numstat</code>, <code>--name-only</code> or <code>--name-status</code> has been given, do not munge pathnames and use NULs as output field terminators.</p> <div class="paragraph"> <p>Without this option, each pathname output will have TAB, LF, double quotes, and backslash characters replaced with <code>\t</code>, <code>\n</code>, <code>\"</code>, and <code>\\</code>, respectively, and the pathname will be enclosed in double quotes if any of those replacements occurred.</p> </div> </dd> <dt class="hdlist1">--name-only</dt> <dd> <p>Show only names of changed files.</p> </dd> <dt class="hdlist1">--name-status</dt> <dd> <p>Show only names and status of changed files. See the description of the <code>--diff-filter</code> option on what the status letters mean.</p> </dd> <dt class="hdlist1">--submodule[=&lt;format&gt;]</dt> <dd> <p>Specify how differences in submodules are shown. When <code>--submodule</code> or <code>--submodule=log</code> is given, the <em>log</em> format is used. This format lists the commits in the range like linkgit:git-submodule[1] <code>summary</code> does. Omitting the <code>--submodule</code> option or specifying <code>--submodule=short</code>, uses the <em>short</em> format. This format just shows the names of the commits at the beginning and end of the range. Can be tweaked via the <code>diff.submodule</code> configuration variable.</p> </dd> <dt class="hdlist1">--color[=&lt;when&gt;]</dt> <dd> <p>Show colored diff. <code>--color</code> (i.e. without <em>=&lt;when&gt;</em>) is the same as <code>--color=always</code>. <em>&lt;when&gt;</em> can be one of <code>always</code>, <code>never</code>, or <code>auto</code>.</p> </dd> <dt class="hdlist1">--no-color</dt> <dd> <p>Turn off colored diff. It is the same as <code>--color=never</code>.</p> </dd> <dt class="hdlist1">--word-diff[=&lt;mode&gt;]</dt> <dd> <p>Show a word diff, using the &lt;mode&gt; to delimit changed words. By default, words are delimited by whitespace; see <code>--word-diff-regex</code> below. The &lt;mode&gt; defaults to <em>plain</em>, and must be one of:</p> <div class="openblock"> <div class="content"> <div class="dlist"> <dl> <dt class="hdlist1">color</dt> <dd> <p>Highlight changed words using only colors. Implies <code>--color</code>.</p> </dd> <dt class="hdlist1">plain</dt> <dd> <p>Show words as <code>[-removed-]</code> and <code>{+added+}</code>. Makes no attempts to escape the delimiters if they appear in the input, so the output may be ambiguous.</p> </dd> <dt class="hdlist1">porcelain</dt> <dd> <p>Use a special line-based format intended for script consumption. Added/removed/unchanged runs are printed in the usual unified diff format, starting with a <code>+</code>/<code>-</code>/` ` character at the beginning of the line and extending to the end of the line. Newlines in the input are represented by a tilde <code>~</code> on a line of its own.</p> </dd> <dt class="hdlist1">none</dt> <dd> <p>Disable word diff again.</p> </dd> </dl> </div> </div> </div> <div class="paragraph"> <p>Note that despite the name of the first mode, color is used to highlight the changed parts in all modes if enabled.</p> </div> </dd> <dt class="hdlist1">--word-diff-regex=&lt;regex&gt;</dt> <dd> <p>Use &lt;regex&gt; to decide what a word is, instead of considering runs of non-whitespace to be a word. Also implies <code>--word-diff</code> unless it was already enabled.</p> <div class="paragraph"> <p>Every non-overlapping match of the &lt;regex&gt; is considered a word. Anything between these matches is considered whitespace and ignored(!) for the purposes of finding differences. You may want to append <code>|[^[:space:]]</code> to your regular expression to make sure that it matches all non-whitespace characters. A match that contains a newline is silently truncated(!) at the newline.</p> </div> <div class="paragraph"> <p>The regex can also be set via a diff driver or configuration option, see linkgit:gitattributes[1] or linkgit:git-config[1]. Giving it explicitly overrides any diff driver or configuration setting. Diff drivers override configuration settings.</p> </div> </dd> <dt class="hdlist1">--color-words[=&lt;regex&gt;]</dt> <dd> <p>Equivalent to <code>--word-diff=color</code> plus (if a regex was specified) <code>--word-diff-regex=&lt;regex&gt;</code>.</p> </dd> <dt class="hdlist1">--no-renames</dt> <dd> <p>Turn off rename detection, even when the configuration file gives the default to do so.</p> </dd> <dt class="hdlist1">--check</dt> <dd> <p>Warn if changes introduce whitespace errors. What are considered whitespace errors is controlled by <code>core.whitespace</code> configuration. By default, trailing whitespaces (including lines that solely consist of whitespaces) and a space character that is immediately followed by a tab character inside the initial indent of the line are considered whitespace errors. Exits with non-zero status if problems are found. Not compatible with --exit-code.</p> </dd> <dt class="hdlist1">--ws-error-highlight=&lt;kind&gt;</dt> <dd> <p>Highlight whitespace errors on lines specified by &lt;kind&gt; in the color specified by <code>color.diff.whitespace</code>. &lt;kind&gt; is a comma separated list of <code>old</code>, <code>new</code>, <code>context</code>. When this option is not given, only whitespace errors in <code>new</code> lines are highlighted. E.g. <code>--ws-error-highlight=new,old</code> highlights whitespace errors on both deleted and added lines. <code>all</code> can be used as a short-hand for <code>old,new,context</code>.</p> </dd> <dt class="hdlist1">--full-index</dt> <dd> <p>Instead of the first handful of characters, show the full pre- and post-image blob object names on the "index" line when generating patch format output.</p> </dd> <dt class="hdlist1">--binary</dt> <dd> <p>In addition to <code>--full-index</code>, output a binary diff that can be applied with <code>git-apply</code>.</p> </dd> <dt class="hdlist1">--abbrev[=&lt;n&gt;]</dt> <dd> <p>Instead of showing the full 40-byte hexadecimal object name in diff-raw format output and diff-tree header lines, show only a partial prefix. This is independent of the <code>--full-index</code> option above, which controls the diff-patch output format. Non default number of digits can be specified with <code>--abbrev=&lt;n&gt;</code>.</p> </dd> <dt class="hdlist1">-B[&lt;n&gt;][/&lt;m&gt;]</dt> <dt class="hdlist1">--break-rewrites[=[&lt;n&gt;][/&lt;m&gt;]]</dt> <dd> <p>Break complete rewrite changes into pairs of delete and create. This serves two purposes:</p> <div class="paragraph"> <p>It affects the way a change that amounts to a total rewrite of a file not as a series of deletion and insertion mixed together with a very few lines that happen to match textually as the context, but as a single deletion of everything old followed by a single insertion of everything new, and the number <code>m</code> controls this aspect of the -B option (defaults to 60%). <code>-B/70%</code> specifies that less than 30% of the original should remain in the result for Git to consider it a total rewrite (i.e. otherwise the resulting patch will be a series of deletion and insertion mixed together with context lines).</p> </div> <div class="paragraph"> <p>When used with -M, a totally-rewritten file is also considered as the source of a rename (usually -M only considers a file that disappeared as the source of a rename), and the number <code>n</code> controls this aspect of the -B option (defaults to 50%). <code>-B20%</code> specifies that a change with addition and deletion compared to 20% or more of the file&#8217;s size are eligible for being picked up as a possible source of a rename to another file.</p> </div> </dd> <dt class="hdlist1">-M[&lt;n&gt;]</dt> <dt class="hdlist1">--find-renames[=&lt;n&gt;]</dt> <dd> <p>Detect renames. If <code>n</code> is specified, it is a threshold on the similarity index (i.e. amount of addition/deletions compared to the file&#8217;s size). For example, <code>-M90%</code> means Git should consider a delete/add pair to be a rename if more than 90% of the file hasn&#8217;t changed. Without a <code>%</code> sign, the number is to be read as a fraction, with a decimal point before it. I.e., <code>-M5</code> becomes 0.5, and is thus the same as <code>-M50%</code>. Similarly, <code>-M05</code> is the same as <code>-M5%</code>. To limit detection to exact renames, use <code>-M100%</code>. The default similarity index is 50%.</p> </dd> <dt class="hdlist1">-C[&lt;n&gt;]</dt> <dt class="hdlist1">--find-copies[=&lt;n&gt;]</dt> <dd> <p>Detect copies as well as renames. See also <code>--find-copies-harder</code>. If <code>n</code> is specified, it has the same meaning as for <code>-M&lt;n&gt;</code>.</p> </dd> <dt class="hdlist1">--find-copies-harder</dt> <dd> <p>For performance reasons, by default, <code>-C</code> option finds copies only if the original file of the copy was modified in the same changeset. This flag makes the command inspect unmodified files as candidates for the source of copy. This is a very expensive operation for large projects, so use it with caution. Giving more than one <code>-C</code> option has the same effect.</p> </dd> <dt class="hdlist1">-D</dt> <dt class="hdlist1">--irreversible-delete</dt> <dd> <p>Omit the preimage for deletes, i.e. print only the header but not the diff between the preimage and <code>/dev/null</code>. The resulting patch is not meant to be applied with <code>patch</code> or <code>git apply</code>; this is solely for people who want to just concentrate on reviewing the text after the change. In addition, the output obviously lack enough information to apply such a patch in reverse, even manually, hence the name of the option.</p> <div class="paragraph"> <p>When used together with <code>-B</code>, omit also the preimage in the deletion part of a delete/create pair.</p> </div> </dd> <dt class="hdlist1">-l&lt;num&gt;</dt> <dd> <p>The <code>-M</code> and <code>-C</code> options require O(n^2) processing time where n is the number of potential rename/copy targets. This option prevents rename/copy detection from running if the number of rename/copy targets exceeds the specified number.</p> </dd> <dt class="hdlist1">--diff-filter=[(A|C|D|M|R|T|U|X|B)&#8230;&#8203;[*]]</dt> <dd> <p>Select only files that are Added (<code>A</code>), Copied (<code>C</code>), Deleted (<code>D</code>), Modified (<code>M</code>), Renamed (<code>R</code>), have their type (i.e. regular file, symlink, submodule, &#8230;&#8203;) changed (<code>T</code>), are Unmerged (<code>U</code>), are Unknown (<code>X</code>), or have had their pairing Broken (<code>B</code>). Any combination of the filter characters (including none) can be used. When <code>*</code> (All-or-none) is added to the combination, all paths are selected if there is any file that matches other criteria in the comparison; if there is no file that matches other criteria, nothing is selected.</p> </dd> <dt class="hdlist1">-S&lt;string&gt;</dt> <dd> <p>Look for differences that change the number of occurrences of the specified string (i.e. addition/deletion) in a file. Intended for the scripter&#8217;s use.</p> <div class="paragraph"> <p>It is useful when you&#8217;re looking for an exact block of code (like a struct), and want to know the history of that block since it first came into being: use the feature iteratively to feed the interesting block in the preimage back into <code>-S</code>, and keep going until you get the very first version of the block.</p> </div> </dd> <dt class="hdlist1">-G&lt;regex&gt;</dt> <dd> <p>Look for differences whose patch text contains added/removed lines that match &lt;regex&gt;.</p> <div class="paragraph"> <p>To illustrate the difference between <code>-S&lt;regex&gt; --pickaxe-regex</code> and <code>-G&lt;regex&gt;</code>, consider a commit with the following diff in the same file:</p> </div> <div class="listingblock"> <div class="content"> <pre>+ return !regexec(regexp, two-&gt;ptr, 1, &amp;regmatch, 0); ... - hit = !regexec(regexp, mf2.ptr, 1, &amp;regmatch, 0);</pre> </div> </div> <div class="paragraph"> <p>While <code>git log -G"regexec\(regexp"</code> will show this commit, <code>git log -S"regexec\(regexp" --pickaxe-regex</code> will not (because the number of occurrences of that string did not change).</p> </div> <div class="paragraph"> <p>See the <em>pickaxe</em> entry in linkgit:gitdiffcore[7] for more information.</p> </div> </dd> <dt class="hdlist1">--pickaxe-all</dt> <dd> <p>When <code>-S</code> or <code>-G</code> finds a change, show all the changes in that changeset, not just the files that contain the change in &lt;string&gt;.</p> </dd> <dt class="hdlist1">--pickaxe-regex</dt> <dd> <p>Treat the &lt;string&gt; given to <code>-S</code> as an extended POSIX regular expression to match.</p> </dd> <dt class="hdlist1">-O&lt;orderfile&gt;</dt> <dd> <p>Output the patch in the order specified in the &lt;orderfile&gt;, which has one shell glob pattern per line. This overrides the <code>diff.orderFile</code> configuration variable (see linkgit:git-config[1]). To cancel <code>diff.orderFile</code>, use <code>-O/dev/null</code>.</p> </dd> <dt class="hdlist1">-R</dt> <dd> <p>Swap two inputs; that is, show differences from index or on-disk file to tree contents.</p> </dd> <dt class="hdlist1">--relative[=&lt;path&gt;]</dt> <dd> <p>When run from a subdirectory of the project, it can be told to exclude changes outside the directory and show pathnames relative to it with this option. When you are not in a subdirectory (e.g. in a bare repository), you can name which subdirectory to make the output relative to by giving a &lt;path&gt; as an argument.</p> </dd> <dt class="hdlist1">-a</dt> <dt class="hdlist1">--text</dt> <dd> <p>Treat all files as text.</p> </dd> <dt class="hdlist1">--ignore-space-at-eol</dt> <dd> <p>Ignore changes in whitespace at EOL.</p> </dd> <dt class="hdlist1">-b</dt> <dt class="hdlist1">--ignore-space-change</dt> <dd> <p>Ignore changes in amount of whitespace. This ignores whitespace at line end, and considers all other sequences of one or more whitespace characters to be equivalent.</p> </dd> <dt class="hdlist1">-w</dt> <dt class="hdlist1">--ignore-all-space</dt> <dd> <p>Ignore whitespace when comparing lines. This ignores differences even if one line has whitespace where the other line has none.</p> </dd> <dt class="hdlist1">--ignore-blank-lines</dt> <dd> <p>Ignore changes whose lines are all blank.</p> </dd> <dt class="hdlist1">--inter-hunk-context=&lt;lines&gt;</dt> <dd> <p>Show the context between diff hunks, up to the specified number of lines, thereby fusing hunks that are close to each other.</p> </dd> <dt class="hdlist1">-W</dt> <dt class="hdlist1">--function-context</dt> <dd> <p>Show whole surrounding functions of changes.</p> </dd> <dt class="hdlist1">--exit-code</dt> <dd> <p>Make the program exit with codes similar to diff(1). That is, it exits with 1 if there were differences and 0 means no differences.</p> </dd> <dt class="hdlist1">--quiet</dt> <dd> <p>Disable all output of the program. Implies <code>--exit-code</code>.</p> </dd> <dt class="hdlist1">--ext-diff</dt> <dd> <p>Allow an external diff helper to be executed. If you set an external diff driver with linkgit:gitattributes[5], you need to use this option with linkgit:git-log[1] and friends.</p> </dd> <dt class="hdlist1">--no-ext-diff</dt> <dd> <p>Disallow external diff drivers.</p> </dd> <dt class="hdlist1">--textconv</dt> <dt class="hdlist1">--no-textconv</dt> <dd> <p>Allow (or disallow) external text conversion filters to be run when comparing binary files. See linkgit:gitattributes[5] for details. Because textconv filters are typically a one-way conversion, the resulting diff is suitable for human consumption, but cannot be applied. For this reason, textconv filters are enabled by default only for linkgit:git-diff[1] and linkgit:git-log[1], but not for linkgit:git-format-patch[1] or diff plumbing commands.</p> </dd> <dt class="hdlist1">--ignore-submodules[=&lt;when&gt;]</dt> <dd> <p>Ignore changes to submodules in the diff generation. &lt;when&gt; can be either "none", "untracked", "dirty" or "all", which is the default. Using "none" will consider the submodule modified when it either contains untracked or modified files or its HEAD differs from the commit recorded in the superproject and can be used to override any settings of the <em>ignore</em> option in linkgit:git-config[1] or linkgit:gitmodules[5]. When "untracked" is used submodules are not considered dirty when they only contain untracked content (but they are still scanned for modified content). Using "dirty" ignores all changes to the work tree of submodules, only changes to the commits stored in the superproject are shown (this was the behavior until 1.7.0). Using "all" hides all changes to submodules.</p> </dd> <dt class="hdlist1">--src-prefix=&lt;prefix&gt;</dt> <dd> <p>Show the given source prefix instead of "a/".</p> </dd> <dt class="hdlist1">--dst-prefix=&lt;prefix&gt;</dt> <dd> <p>Show the given destination prefix instead of "b/".</p> </dd> <dt class="hdlist1">--no-prefix</dt> <dd> <p>Do not show any source or destination prefix.</p> </dd> </dl> </div> <div class="paragraph"> <p>For more detailed explanation on these common options, see also linkgit:gitdiffcore[7].</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">&lt;tree-ish&gt;</dt> <dd> <p>The id of a tree object.</p> </dd> <dt class="hdlist1">&lt;path&gt;&#8230;&#8203;</dt> <dd> <p>If provided, the results are limited to a subset of files matching one of these prefix strings. i.e., file matches <code>/^&lt;pattern1&gt;|&lt;pattern2&gt;|.../</code> Note that this parameter does not provide any wildcard or regexp features.</p> </dd> <dt class="hdlist1">-r</dt> <dd> <p>recurse into sub-trees</p> </dd> <dt class="hdlist1">-t</dt> <dd> <p>show tree entry itself as well as subtrees. Implies -r.</p> </dd> <dt class="hdlist1">--root</dt> <dd> <p>When <em>--root</em> is specified the initial commit will be shown as a big creation event. This is equivalent to a diff against the NULL tree.</p> </dd> <dt class="hdlist1">--stdin</dt> <dd> <p>When <em>--stdin</em> is specified, the command does not take &lt;tree-ish&gt; arguments from the command line. Instead, it reads lines containing either two &lt;tree&gt;, one &lt;commit&gt;, or a list of &lt;commit&gt; from its standard input. (Use a single space as separator.)</p> <div class="paragraph"> <p>When two trees are given, it compares the first tree with the second. When a single commit is given, it compares the commit with its parents. The remaining commits, when given, are used as if they are parents of the first commit.</p> </div> <div class="paragraph"> <p>When comparing two trees, the ID of both trees (separated by a space and terminated by a newline) is printed before the difference. When comparing commits, the ID of the first (or only) commit, followed by a newline, is printed.</p> </div> <div class="paragraph"> <p>The following flags further affect the behavior when comparing commits (but not trees).</p> </div> </dd> <dt class="hdlist1">-m</dt> <dd> <p>By default, <em>git diff-tree --stdin</em> does not show differences for merge commits. With this flag, it shows differences to that commit from all of its parents. See also <em>-c</em>.</p> </dd> <dt class="hdlist1">-s</dt> <dd> <p>By default, <em>git diff-tree --stdin</em> shows differences, either in machine-readable form (without <em>-p</em>) or in patch form (with <em>-p</em>). This output can be suppressed. It is only useful with <em>-v</em> flag.</p> </dd> <dt class="hdlist1">-v</dt> <dd> <p>This flag causes <em>git diff-tree --stdin</em> to also show the commit message before the differences.</p> </dd> <dt class="hdlist1">--pretty[=&lt;format&gt;]</dt> <dt class="hdlist1">--format=&lt;format&gt;</dt> <dd> <p>Pretty-print the contents of the commit logs in a given format, where <em>&lt;format&gt;</em> can be one of <em>oneline</em>, <em>short</em>, <em>medium</em>, <em>full</em>, <em>fuller</em>, <em>email</em>, <em>raw</em>, <em>format:&lt;string&gt;</em> and <em>tformat:&lt;string&gt;</em>. When <em>&lt;format&gt;</em> is none of the above, and has <em>%placeholder</em> in it, it acts as if <em>--pretty=tformat:&lt;format&gt;</em> were given.</p> <div class="paragraph"> <p>See the "PRETTY FORMATS" section for some additional details for each format. When <em>=&lt;format&gt;</em> part is omitted, it defaults to <em>medium</em>.</p> </div> <div class="paragraph"> <p>Note: you can specify the default pretty format in the repository configuration (see linkgit:git-config[1]).</p> </div> </dd> <dt class="hdlist1">--abbrev-commit</dt> <dd> <p>Instead of showing the full 40-byte hexadecimal commit object name, show only a partial prefix. Non default number of digits can be specified with "--abbrev=&lt;n&gt;" (which also modifies diff output, if it is displayed).</p> <div class="paragraph"> <p>This should make "--pretty=oneline" a whole lot more readable for people using 80-column terminals.</p> </div> </dd> <dt class="hdlist1">--no-abbrev-commit</dt> <dd> <p>Show the full 40-byte hexadecimal commit object name. This negates <code>--abbrev-commit</code> and those options which imply it such as "--oneline". It also overrides the <em>log.abbrevCommit</em> variable.</p> </dd> <dt class="hdlist1">--oneline</dt> <dd> <p>This is a shorthand for "--pretty=oneline --abbrev-commit" used together.</p> </dd> <dt class="hdlist1">--encoding=&lt;encoding&gt;</dt> <dd> <p>The commit objects record the encoding used for the log message in their encoding header; this option can be used to tell the command to re-code the commit log message in the encoding preferred by the user. For non plumbing commands this defaults to UTF-8. Note that if an object claims to be encoded in <code>X</code> and we are outputting in <code>X</code>, we will output the object verbatim; this means that invalid sequences in the original commit may be copied to the output.</p> </dd> <dt class="hdlist1">--notes[=&lt;ref&gt;]</dt> <dd> <p>Show the notes (see linkgit:git-notes[1]) that annotate the commit, when showing the commit log message. This is the default for <code>git log</code>, <code>git show</code> and <code>git whatchanged</code> commands when there is no <code>--pretty</code>, <code>--format</code>, or <code>--oneline</code> option given on the command line.</p> <div class="paragraph"> <p>By default, the notes shown are from the notes refs listed in the <em>core.notesRef</em> and <em>notes.displayRef</em> variables (or corresponding environment overrides). See linkgit:git-config[1] for more details.</p> </div> <div class="paragraph"> <p>With an optional <em>&lt;ref&gt;</em> argument, show this notes ref instead of the default notes ref(s). The ref is taken to be in <code>refs/notes/</code> if it is not qualified.</p> </div> <div class="paragraph"> <p>Multiple --notes options can be combined to control which notes are being displayed. Examples: "--notes=foo" will show only notes from "refs/notes/foo"; "--notes=foo --notes" will show both notes from "refs/notes/foo" and from the default notes ref(s).</p> </div> </dd> <dt class="hdlist1">--no-notes</dt> <dd> <p>Do not show notes. This negates the above <code>--notes</code> option, by resetting the list of notes refs from which notes are shown. Options are parsed in the order given on the command line, so e.g. "--notes --notes=foo --no-notes --notes=bar" will only show notes from "refs/notes/bar".</p> </dd> <dt class="hdlist1">--show-notes[=&lt;ref&gt;]</dt> <dt class="hdlist1">--[no-]standard-notes</dt> <dd> <p>These options are deprecated. Use the above --notes/--no-notes options instead.</p> </dd> <dt class="hdlist1">--show-signature</dt> <dd> <p>Check the validity of a signed commit object by passing the signature to <code>gpg --verify</code> and show the output.</p> </dd> <dt class="hdlist1">--no-commit-id</dt> <dd> <p><em>git diff-tree</em> outputs a line with the commit ID when applicable. This flag suppressed the commit ID output.</p> </dd> <dt class="hdlist1">-c</dt> <dd> <p>This flag changes the way a merge commit is displayed (which means it is useful only when the command is given one &lt;tree-ish&gt;, or <em>--stdin</em>). It shows the differences from each of the parents to the merge result simultaneously instead of showing pairwise diff between a parent and the result one at a time (which is what the <em>-m</em> option does). Furthermore, it lists only files which were modified from all parents.</p> </dd> <dt class="hdlist1">--cc</dt> <dd> <p>This flag changes the way a merge commit patch is displayed, in a similar way to the <em>-c</em> option. It implies the <em>-c</em> and <em>-p</em> options and further compresses the patch output by omitting uninteresting hunks whose the contents in the parents have only two variants and the merge result picks one of them without modification. When all hunks are uninteresting, the commit itself and the commit log message is not shown, just like in any other "empty diff" case.</p> </dd> <dt class="hdlist1">--always</dt> <dd> <p>Show the commit itself and the commit log message even if the diff itself is empty.</p> </dd> </dl> </div> </div> </div> <div class="sect1"> <h2 id="_pretty_formats">PRETTY FORMATS</h2> <div class="sectionbody"> <div class="paragraph"> <p>If the commit is a merge, and if the pretty-format is not <em>oneline</em>, <em>email</em> or <em>raw</em>, an additional line is inserted before the <em>Author:</em> line. This line begins with "Merge: " and the sha1s of ancestral commits are printed, separated by spaces. Note that the listed commits may not necessarily be the list of the <strong>direct</strong> parent commits if you have limited your view of history: for example, if you are only interested in changes related to a certain directory or file.</p> </div> <div class="paragraph"> <p>There are several built-in formats, and you can define additional formats by setting a pretty.&lt;name&gt; config option to either another format name, or a <em>format:</em> string, as described below (see linkgit:git-config[1]). Here are the details of the built-in formats:</p> </div> <div class="ulist"> <ul> <li> <p><em>oneline</em></p> <div class="literalblock"> <div class="content"> <pre>&lt;sha1&gt; &lt;title line&gt;</pre> </div> </div> <div class="paragraph"> <p>This is designed to be as compact as possible.</p> </div> </li> <li> <p><em>short</em></p> <div class="literalblock"> <div class="content"> <pre>commit &lt;sha1&gt; Author: &lt;author&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;title line&gt;</pre> </div> </div> </li> <li> <p><em>medium</em></p> <div class="literalblock"> <div class="content"> <pre>commit &lt;sha1&gt; Author: &lt;author&gt; Date: &lt;author date&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;title line&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;full commit message&gt;</pre> </div> </div> </li> <li> <p><em>full</em></p> <div class="literalblock"> <div class="content"> <pre>commit &lt;sha1&gt; Author: &lt;author&gt; Commit: &lt;committer&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;title line&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;full commit message&gt;</pre> </div> </div> </li> <li> <p><em>fuller</em></p> <div class="literalblock"> <div class="content"> <pre>commit &lt;sha1&gt; Author: &lt;author&gt; AuthorDate: &lt;author date&gt; Commit: &lt;committer&gt; CommitDate: &lt;committer date&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;title line&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;full commit message&gt;</pre> </div> </div> </li> <li> <p><em>email</em></p> <div class="literalblock"> <div class="content"> <pre>From &lt;sha1&gt; &lt;date&gt; From: &lt;author&gt; Date: &lt;author date&gt; Subject: [PATCH] &lt;title line&gt;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>&lt;full commit message&gt;</pre> </div> </div> </li> <li> <p><em>raw</em></p> <div class="paragraph"> <p>The <em>raw</em> format shows the entire commit exactly as stored in the commit object. Notably, the SHA-1s are displayed in full, regardless of whether --abbrev or --no-abbrev are used, and <em>parents</em> information show the true parent commits, without taking grafts or history simplification into account. Note that this format affects the way commits are displayed, but not the way the diff is shown e.g. with <code>git log --raw</code>. To get full object names in a raw diff format, use <code>--no-abbrev</code>.</p> </div> </li> <li> <p><em>format:&lt;string&gt;</em></p> <div class="paragraph"> <p>The <em>format:&lt;string&gt;</em> format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with <em>%n</em> instead of <em>\n</em>.</p> </div> <div class="paragraph"> <p>E.g, <em>format:"The author of %h was %an, %ar%nThe title was &gt;&gt;%s&lt;&lt;%n"</em> would show something like this:</p> </div> <div class="listingblock"> <div class="content"> <pre>The author of fe6e0ee was Junio C Hamano, 23 hours ago The title was &gt;&gt;t4119: test autocomputing -p&lt;n&gt; for traditional diff input.&lt;&lt;</pre> </div> </div> <div class="paragraph"> <p>The placeholders are:</p> </div> <div class="ulist"> <ul> <li> <p><em>%H</em>: commit hash</p> </li> <li> <p><em>%h</em>: abbreviated commit hash</p> </li> <li> <p><em>%T</em>: tree hash</p> </li> <li> <p><em>%t</em>: abbreviated tree hash</p> </li> <li> <p><em>%P</em>: parent hashes</p> </li> <li> <p><em>%p</em>: abbreviated parent hashes</p> </li> <li> <p><em>%an</em>: author name</p> </li> <li> <p><em>%aN</em>: author name (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%ae</em>: author email</p> </li> <li> <p><em>%aE</em>: author email (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%ad</em>: author date (format respects --date= option)</p> </li> <li> <p><em>%aD</em>: author date, RFC2822 style</p> </li> <li> <p><em>%ar</em>: author date, relative</p> </li> <li> <p><em>%at</em>: author date, UNIX timestamp</p> </li> <li> <p><em>%ai</em>: author date, ISO 8601-like format</p> </li> <li> <p><em>%aI</em>: author date, strict ISO 8601 format</p> </li> <li> <p><em>%cn</em>: committer name</p> </li> <li> <p><em>%cN</em>: committer name (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%ce</em>: committer email</p> </li> <li> <p><em>%cE</em>: committer email (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%cd</em>: committer date (format respects --date= option)</p> </li> <li> <p><em>%cD</em>: committer date, RFC2822 style</p> </li> <li> <p><em>%cr</em>: committer date, relative</p> </li> <li> <p><em>%ct</em>: committer date, UNIX timestamp</p> </li> <li> <p><em>%ci</em>: committer date, ISO 8601-like format</p> </li> <li> <p><em>%cI</em>: committer date, strict ISO 8601 format</p> </li> <li> <p><em>%d</em>: ref names, like the --decorate option of linkgit:git-log[1]</p> </li> <li> <p><em>%D</em>: ref names without the " (", ")" wrapping.</p> </li> <li> <p><em>%e</em>: encoding</p> </li> <li> <p><em>%s</em>: subject</p> </li> <li> <p><em>%f</em>: sanitized subject line, suitable for a filename</p> </li> <li> <p><em>%b</em>: body</p> </li> <li> <p><em>%B</em>: raw body (unwrapped subject and body)</p> </li> <li> <p><em>%N</em>: commit notes</p> </li> <li> <p><em>%GG</em>: raw verification message from GPG for a signed commit</p> </li> <li> <p><em>%G?</em>: show "G" for a Good signature, "B" for a Bad signature, "U" for a good, untrusted signature and "N" for no signature</p> </li> <li> <p><em>%GS</em>: show the name of the signer for a signed commit</p> </li> <li> <p><em>%GK</em>: show the key used to sign a signed commit</p> </li> <li> <p><em>%gD</em>: reflog selector, e.g., <code>refs/stash@{1}</code></p> </li> <li> <p><em>%gd</em>: shortened reflog selector, e.g., <code>stash@{1}</code></p> </li> <li> <p><em>%gn</em>: reflog identity name</p> </li> <li> <p><em>%gN</em>: reflog identity name (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%ge</em>: reflog identity email</p> </li> <li> <p><em>%gE</em>: reflog identity email (respecting .mailmap, see linkgit:git-shortlog[1] or linkgit:git-blame[1])</p> </li> <li> <p><em>%gs</em>: reflog subject</p> </li> <li> <p><em>%Cred</em>: switch color to red</p> </li> <li> <p><em>%Cgreen</em>: switch color to green</p> </li> <li> <p><em>%Cblue</em>: switch color to blue</p> </li> <li> <p><em>%Creset</em>: reset color</p> </li> <li> <p><em>%C(&#8230;&#8203;)</em>: color specification, as described in color.branch.* config option; adding <code>auto,</code> at the beginning will emit color only when colors are enabled for log output (by <code>color.diff</code>, <code>color.ui</code>, or <code>--color</code>, and respecting the <code>auto</code> settings of the former if we are going to a terminal). <code>auto</code> alone (i.e. <code>%C(auto)</code>) will turn on auto coloring on the next placeholders until the color is switched again.</p> </li> <li> <p><em>%m</em>: left, right or boundary mark</p> </li> <li> <p><em>%n</em>: newline</p> </li> <li> <p><em>%%</em>: a raw <em>%</em></p> </li> <li> <p><em>%x00</em>: print a byte from a hex code</p> </li> <li> <p><em>%w([&lt;w&gt;[,&lt;i1&gt;[,&lt;i2&gt;]]])</em>: switch line wrapping, like the -w option of linkgit:git-shortlog[1].</p> </li> <li> <p><em>%&lt;(&lt;N&gt;[,trunc|ltrunc|mtrunc])</em>: make the next placeholder take at least N columns, padding spaces on the right if necessary. Optionally truncate at the beginning (ltrunc), the middle (mtrunc) or the end (trunc) if the output is longer than N columns. Note that truncating only works correctly with N &gt;= 2.</p> </li> <li> <p><em>%&lt;|(&lt;N&gt;)</em>: make the next placeholder take at least until Nth columns, padding spaces on the right if necessary</p> </li> <li> <p><em>%&gt;(&lt;N&gt;)</em>, <em>%&gt;|(&lt;N&gt;)</em>: similar to <em>%&lt;(&lt;N&gt;)</em>, <em>%&lt;|(&lt;N&gt;)</em> respectively, but padding spaces on the left</p> </li> <li> <p><em>%&gt;&gt;(&lt;N&gt;)</em>, <em>%&gt;&gt;|(&lt;N&gt;)</em>: similar to <em>%&gt;(&lt;N&gt;)</em>, <em>%&gt;|(&lt;N&gt;)</em> respectively, except that if the next placeholder takes more spaces than given and there are spaces on its left, use those spaces</p> </li> <li> <p><em>%&gt;&lt;(&lt;N&gt;)</em>, <em>%&gt;&lt;|(&lt;N&gt;)</em>: similar to <em>% &lt;(&lt;N&gt;)</em>, <em>%&lt;|(&lt;N&gt;)</em> respectively, but padding both sides (i.e. the text is centered)</p> </li> </ul> </div> </li> </ul> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> Some placeholders may depend on other options given to the revision traversal engine. For example, the <code>%g*</code> reflog options will insert an empty string unless we are traversing reflog entries (e.g., by <code>git log -g</code>). The <code>%d</code> and <code>%D</code> placeholders will use the "short" decoration format if <code>--decorate</code> was not already provided on the command line. </td> </tr> </table> </div> <div class="paragraph"> <p>If you add a <code>+</code> (plus sign) after <em>%</em> of a placeholder, a line-feed is inserted immediately before the expansion if and only if the placeholder expands to a non-empty string.</p> </div> <div class="paragraph"> <p>If you add a <code>-</code> (minus sign) after <em>%</em> of a placeholder, line-feeds that immediately precede the expansion are deleted if and only if the placeholder expands to an empty string.</p> </div> <div class="paragraph"> <p>If you add a ` ` (space) after <em>%</em> of a placeholder, a space is inserted immediately before the expansion if and only if the placeholder expands to a non-empty string.</p> </div> <div class="ulist"> <ul> <li> <p><em>tformat:</em></p> <div class="paragraph"> <p>The <em>tformat:</em> format works exactly like <em>format:</em>, except that it provides "terminator" semantics instead of "separator" semantics. In other words, each commit has the message terminator character (usually a newline) appended, rather than a separator placed between entries. This means that the final entry of a single-line format will be properly terminated with a new line, just as the "oneline" format does. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre>$ git log -2 --pretty=format:%h 4da45bef \ | perl -pe '$_ .= " -- NO NEWLINE\n" unless /\n/' 4da45be 7134973 -- NO NEWLINE $ git log -2 --pretty=tformat:%h 4da45bef \ | perl -pe '$_ .= " -- NO NEWLINE\n" unless /\n/' 4da45be 7134973</pre> </div> </div> <div class="paragraph"> <p>In addition, any unrecognized string that has a <code>%</code> in it is interpreted as if it has <code>tformat:</code> in front of it. For example, these two are equivalent:</p> </div> <div class="listingblock"> <div class="content"> <pre>$ git log -2 --pretty=tformat:%h 4da45bef $ git log -2 --pretty=%h 4da45bef</pre> </div> </div> </li> </ul> </div> </div> </div> <div class="sect1"> <h2 id="_limiting_output">Limiting Output</h2> <div class="sectionbody"> <div class="paragraph"> <p>If you&#8217;re only interested in differences in a subset of files, for example some architecture-specific files, you might do:</p> </div> <div class="literalblock"> <div class="content"> <pre>git diff-tree -r &lt;tree-ish&gt; &lt;tree-ish&gt; arch/ia64 include/asm-ia64</pre> </div> </div> <div class="paragraph"> <p>and it will only show you what changed in those two directories.</p> </div> <div class="paragraph"> <p>Or if you are searching for what changed in just <code>kernel/sched.c</code>, just do</p> </div> <div class="literalblock"> <div class="content"> <pre>git diff-tree -r &lt;tree-ish&gt; &lt;tree-ish&gt; kernel/sched.c</pre> </div> </div> <div class="paragraph"> <p>and it will ignore all differences to other files.</p> </div> <div class="paragraph"> <p>The pattern is always the prefix, and is matched exactly. There are no wildcards. Even stricter, it has to match a complete path component. I.e. "foo" does not pick up <code>foobar.h</code>. "foo" does match <code>foo/bar.h</code> so it can be used to name subdirectories.</p> </div> <div class="paragraph"> <p>An example of normal usage is:</p> </div> <div class="literalblock"> <div class="content"> <pre>torvalds@ppc970:~/git&gt; git diff-tree --abbrev 5319e4 :100664 100664 ac348b... a01513... git-fsck-objects.c</pre> </div> </div> <div class="paragraph"> <p>which tells you that the last commit changed just one file (it&#8217;s from this one:</p> </div> <div class="listingblock"> <div class="content"> <pre>commit 3c6f7ca19ad4043e9e72fa94106f352897e651a8 tree 5319e4d609cdd282069cc4dce33c1db559539b03 parent b4e628ea30d5ab3606119d2ea5caeab141d38df7 author Linus Torvalds &lt;[email protected]&gt; Sat Apr 9 12:02:30 2005 committer Linus Torvalds &lt;[email protected]&gt; Sat Apr 9 12:02:30 2005 Make "git-fsck-objects" print out all the root commits it finds. Once I do the reference tracking, I'll also make it print out all the HEAD commits it finds, which is even more interesting.</pre> </div> </div> <div class="paragraph"> <p>in case you care).</p> </div> </div> </div> <div class="sect1"> <h2 id="_raw_output_format">Raw output format</h2> <div class="sectionbody"> <div class="paragraph"> <p>The raw output format from "git-diff-index", "git-diff-tree", "git-diff-files" and "git diff --raw" are very similar.</p> </div> <div class="paragraph"> <p>These commands all compare two sets of things; what is compared differs:</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">git-diff-index &lt;tree-ish&gt;</dt> <dd> <p>compares the &lt;tree-ish&gt; and the files on the filesystem.</p> </dd> <dt class="hdlist1">git-diff-index --cached &lt;tree-ish&gt;</dt> <dd> <p>compares the &lt;tree-ish&gt; and the index.</p> </dd> <dt class="hdlist1">git-diff-tree [-r] &lt;tree-ish-1&gt; &lt;tree-ish-2&gt; [&lt;pattern&gt;&#8230;&#8203;]</dt> <dd> <p>compares the trees named by the two arguments.</p> </dd> <dt class="hdlist1">git-diff-files [&lt;pattern&gt;&#8230;&#8203;]</dt> <dd> <p>compares the index and the files on the filesystem.</p> </dd> </dl> </div> <div class="paragraph"> <p>The "git-diff-tree" command begins its output by printing the hash of what is being compared. After that, all the commands print one output line per changed file.</p> </div> <div class="paragraph"> <p>An output line is formatted this way:</p> </div> <div class="listingblock"> <div class="content"> <pre>in-place edit :100644 100644 bcd1234... 0123456... M file0 copy-edit :100644 100644 abcd123... 1234567... C68 file1 file2 rename-edit :100644 100644 abcd123... 1234567... R86 file1 file3 create :000000 100644 0000000... 1234567... A file4 delete :100644 000000 1234567... 0000000... D file5 unmerged :000000 000000 0000000... 0000000... U file6</pre> </div> </div> <div class="paragraph"> <p>That is, from the left to the right:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>a colon.</p> </li> <li> <p>mode for "src"; 000000 if creation or unmerged.</p> </li> <li> <p>a space.</p> </li> <li> <p>mode for "dst"; 000000 if deletion or unmerged.</p> </li> <li> <p>a space.</p> </li> <li> <p>sha1 for "src"; 0{40} if creation or unmerged.</p> </li> <li> <p>a space.</p> </li> <li> <p>sha1 for "dst"; 0{40} if creation, unmerged or "look at work tree".</p> </li> <li> <p>a space.</p> </li> <li> <p>status, followed by optional "score" number.</p> </li> <li> <p>a tab or a NUL when <em>-z</em> option is used.</p> </li> <li> <p>path for "src"</p> </li> <li> <p>a tab or a NUL when <em>-z</em> option is used; only exists for C or R.</p> </li> <li> <p>path for "dst"; only exists for C or R.</p> </li> <li> <p>an LF or a NUL when <em>-z</em> option is used, to terminate the record.</p> </li> </ol> </div> <div class="paragraph"> <p>Possible status letters are:</p> </div> <div class="ulist"> <ul> <li> <p>A: addition of a file</p> </li> <li> <p>C: copy of a file into a new one</p> </li> <li> <p>D: deletion of a file</p> </li> <li> <p>M: modification of the contents or mode of a file</p> </li> <li> <p>R: renaming of a file</p> </li> <li> <p>T: change in the type of the file</p> </li> <li> <p>U: file is unmerged (you must complete the merge before it can be committed)</p> </li> <li> <p>X: "unknown" change type (most probably a bug, please report it)</p> </li> </ul> </div> <div class="paragraph"> <p>Status letters C and R are always followed by a score (denoting the percentage of similarity between the source and target of the move or copy). Status letter M may be followed by a score (denoting the percentage of dissimilarity) for file rewrites.</p> </div> <div class="paragraph"> <p>&lt;sha1&gt; is shown as all 0&#8217;s if a file is new on the filesystem and it is out of sync with the index.</p> </div> <div class="paragraph"> <p>Example:</p> </div> <div class="listingblock"> <div class="content"> <pre>:100644 100644 5be4a4...... 000000...... M file.c</pre> </div> </div> <div class="paragraph"> <p>When <code>-z</code> option is not used, TAB, LF, and backslash characters in pathnames are represented as <code>\t</code>, <code>\n</code>, and <code>\\</code>, respectively.</p> </div> </div> </div> <div class="sect1"> <h2 id="_diff_format_for_merges">diff format for merges</h2> <div class="sectionbody"> <div class="paragraph"> <p>"git-diff-tree", "git-diff-files" and "git-diff --raw" can take <em>-c</em> or <em>--cc</em> option to generate diff output also for merge commits. The output differs from the format described above in the following way:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>there is a colon for each parent</p> </li> <li> <p>there are more "src" modes and "src" sha1</p> </li> <li> <p>status is concatenated status characters for each parent</p> </li> <li> <p>no optional "score" number</p> </li> <li> <p>single path, only for "dst"</p> </li> </ol> </div> <div class="paragraph"> <p>Example:</p> </div> <div class="listingblock"> <div class="content"> <pre>::100644 100644 100644 fabadb8... cc95eb0... 4866510... MM describe.c</pre> </div> </div> <div class="paragraph"> <p>Note that <em>combined diff</em> lists only files which were modified from all parents.</p> </div> </div> </div> <div class="sect1"> <h2 id="_generating_patches_with_p">Generating patches with -p</h2> <div class="sectionbody"> <div class="paragraph"> <p>When "git-diff-index", "git-diff-tree", or "git-diff-files" are run with a <em>-p</em> option, "git diff" without the <em>--raw</em> option, or "git log" with the "-p" option, they do not produce the output described above; instead they produce a patch file. You can customize the creation of such patches via the GIT_EXTERNAL_DIFF and the GIT_DIFF_OPTS environment variables.</p> </div> <div class="paragraph"> <p>What the -p option produces is slightly different from the traditional diff format:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>It is preceded with a "git diff" header that looks like this:</p> <div class="literalblock"> <div class="content"> <pre>diff --git a/file1 b/file2</pre> </div> </div> <div class="paragraph"> <p>The <code>a/</code> and <code>b/</code> filenames are the same unless rename/copy is involved. Especially, even for a creation or a deletion, <code>/dev/null</code> is <em>not</em> used in place of the <code>a/</code> or <code>b/</code> filenames.</p> </div> <div class="paragraph"> <p>When rename/copy is involved, <code>file1</code> and <code>file2</code> show the name of the source file of the rename/copy and the name of the file that rename/copy produces, respectively.</p> </div> </li> <li> <p>It is followed by one or more extended header lines:</p> <div class="literalblock"> <div class="content"> <pre>old mode &lt;mode&gt; new mode &lt;mode&gt; deleted file mode &lt;mode&gt; new file mode &lt;mode&gt; copy from &lt;path&gt; copy to &lt;path&gt; rename from &lt;path&gt; rename to &lt;path&gt; similarity index &lt;number&gt; dissimilarity index &lt;number&gt; index &lt;hash&gt;..&lt;hash&gt; &lt;mode&gt;</pre> </div> </div> <div class="paragraph"> <p>File modes are printed as 6-digit octal numbers including the file type and file permission bits.</p> </div> <div class="paragraph"> <p>Path names in extended headers do not include the <code>a/</code> and <code>b/</code> prefixes.</p> </div> <div class="paragraph"> <p>The similarity index is the percentage of unchanged lines, and the dissimilarity index is the percentage of changed lines. It is a rounded down integer, followed by a percent sign. The similarity index value of 100% is thus reserved for two equal files, while 100% dissimilarity means that no line from the old file made it into the new one.</p> </div> <div class="paragraph"> <p>The index line includes the SHA-1 checksum before and after the change. The &lt;mode&gt; is included if the file mode does not change; otherwise, separate lines indicate the old and the new mode.</p> </div> </li> <li> <p>TAB, LF, double quote and backslash characters in pathnames are represented as <code>\t</code>, <code>\n</code>, <code>\"</code> and <code>\\</code>, respectively. If there is need for such substitution then the whole pathname is put in double quotes.</p> </li> <li> <p>All the <code>file1</code> files in the output refer to files before the commit, and all the <code>file2</code> files refer to files after the commit. It is incorrect to apply each change to each file sequentially. For example, this patch will swap a and b:</p> <div class="literalblock"> <div class="content"> <pre>diff --git a/a b/b rename from a rename to b diff --git a/b b/a rename from b rename to a</pre> </div> </div> </li> </ol> </div> </div> </div> <div class="sect1"> <h2 id="_combined_diff_format">combined diff format</h2> <div class="sectionbody"> <div class="paragraph"> <p>Any diff-generating command can take the <code>-c</code> or <code>--cc</code> option to produce a <em>combined diff</em> when showing a merge. This is the default format when showing merges with linkgit:git-diff[1] or linkgit:git-show[1]. Note also that you can give the <code>-m</code> option to any of these commands to force generation of diffs with individual parents of a merge.</p> </div> <div class="paragraph"> <p>A <em>combined diff</em> format looks like this:</p> </div> <div class="listingblock"> <div class="content"> <pre>diff --combined describe.c index fabadb8,cc95eb0..4866510 --- a/describe.c +++ b/describe.c @@@ -98,20 -98,12 +98,20 @@@ return (a_date &gt; b_date) ? -1 : (a_date == b_date) ? 0 : 1; } - static void describe(char *arg) -static void describe(struct commit *cmit, int last_one) ++static void describe(char *arg, int last_one) { + unsigned char sha1[20]; + struct commit *cmit; struct commit_list *list; static int initialized = 0; struct commit_name *n; + if (get_sha1(arg, sha1) &lt; 0) + usage(describe_usage); + cmit = lookup_commit_reference(sha1); + if (!cmit) + usage(describe_usage); + if (!initialized) { initialized = 1; for_each_ref(get_name);</pre> </div> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>It is preceded with a "git diff" header, that looks like this (when <em>-c</em> option is used):</p> <div class="literalblock"> <div class="content"> <pre>diff --combined file</pre> </div> </div> <div class="paragraph"> <p>or like this (when <em>--cc</em> option is used):</p> </div> <div class="literalblock"> <div class="content"> <pre>diff --cc file</pre> </div> </div> </li> <li> <p>It is followed by one or more extended header lines (this example shows a merge with two parents):</p> <div class="literalblock"> <div class="content"> <pre>index &lt;hash&gt;,&lt;hash&gt;..&lt;hash&gt; mode &lt;mode&gt;,&lt;mode&gt;..&lt;mode&gt; new file mode &lt;mode&gt; deleted file mode &lt;mode&gt;,&lt;mode&gt;</pre> </div> </div> <div class="paragraph"> <p>The <code>mode &lt;mode&gt;,&lt;mode&gt;..&lt;mode&gt;</code> line appears only if at least one of the &lt;mode&gt; is different from the rest. Extended headers with information about detected contents movement (renames and copying detection) are designed to work with diff of two &lt;tree-ish&gt; and are not used by combined diff format.</p> </div> </li> <li> <p>It is followed by two-line from-file/to-file header</p> <div class="literalblock"> <div class="content"> <pre>--- a/file +++ b/file</pre> </div> </div> <div class="paragraph"> <p>Similar to two-line header for traditional <em>unified</em> diff format, <code>/dev/null</code> is used to signal created or deleted files.</p> </div> </li> <li> <p>Chunk header format is modified to prevent people from accidentally feeding it to <code>patch -p1</code>. Combined diff format was created for review of merge commit changes, and was not meant for apply. The change is similar to the change in the extended <em>index</em> header:</p> <div class="literalblock"> <div class="content"> <pre>@@@ &lt;from-file-range&gt; &lt;from-file-range&gt; &lt;to-file-range&gt; @@@</pre> </div> </div> <div class="paragraph"> <p>There are (number of parents + 1) <code>@</code> characters in the chunk header for combined diff format.</p> </div> </li> </ol> </div> <div class="paragraph"> <p>Unlike the traditional <em>unified</em> diff format, which shows two files A and B with a single column that has <code>-</code> (minus&#8201;&#8212;&#8201;appears in A but removed in B), <code>+</code> (plus&#8201;&#8212;&#8201;missing in A but added to B), or <code>" "</code> (space&#8201;&#8212;&#8201;unchanged) prefix, this format compares two or more files file1, file2,&#8230;&#8203; with one file X, and shows how X differs from each of fileN. One column for each of fileN is prepended to the output line to note how X&#8217;s line is different from it.</p> </div> <div class="paragraph"> <p>A <code>-</code> character in the column N means that the line appears in fileN but it does not appear in the result. A <code>+</code> character in the column N means that the line appears in the result, and fileN does not have that line (in other words, the line was added, from the point of view of that parent).</p> </div> <div class="paragraph"> <p>In the above example output, the function signature was changed from both files (hence two <code>-</code> removals from both file1 and file2, plus <code>++</code> to mean one line that was added does not appear in either file1 or file2). Also eight other lines are the same from file1 but do not appear in file2 (hence prefixed with <code>+</code>).</p> </div> <div class="paragraph"> <p>When shown by <code>git diff-tree -c</code>, it compares the parents of a merge commit with the merge result (i.e. file1..fileN are the parents). When shown by <code>git diff-files -c</code>, it compares the two unresolved merge parents with the working tree file (i.e. file1 is stage 2 aka "our version", file2 is stage 3 aka "their version").</p> </div> </div> </div> <div class="sect1"> <h2 id="_other_diff_formats">other diff formats</h2> <div class="sectionbody"> <div class="paragraph"> <p>The <code>--summary</code> option describes newly added, deleted, renamed and copied files. The <code>--stat</code> option adds diffstat(1) graph to the output. These options can be combined with other options, such as <code>-p</code>, and are meant for human consumption.</p> </div> <div class="paragraph"> <p>When showing a change that involves a rename or a copy, <code>--stat</code> output formats the pathnames compactly by combining common prefix and suffix of the pathnames. For example, a change that moves <code>arch/i386/Makefile</code> to <code>arch/x86/Makefile</code> while modifying 4 lines will be shown like this:</p> </div> <div class="listingblock"> <div class="content"> <pre>arch/{i386 =&gt; x86}/Makefile | 4 +--</pre> </div> </div> <div class="paragraph"> <p>The <code>--numstat</code> option gives the diffstat(1) information but is designed for easier machine consumption. An entry in <code>--numstat</code> output looks like this:</p> </div> <div class="listingblock"> <div class="content"> <pre>1 2 README 3 1 arch/{i386 =&gt; x86}/Makefile</pre> </div> </div> <div class="paragraph"> <p>That is, from left to right:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>the number of added lines;</p> </li> <li> <p>a tab;</p> </li> <li> <p>the number of deleted lines;</p> </li> <li> <p>a tab;</p> </li> <li> <p>pathname (possibly with rename/copy information);</p> </li> <li> <p>a newline.</p> </li> </ol> </div> <div class="paragraph"> <p>When <code>-z</code> output option is in effect, the output is formatted this way:</p> </div> <div class="listingblock"> <div class="content"> <pre>1 2 README NUL 3 1 NUL arch/i386/Makefile NUL arch/x86/Makefile NUL</pre> </div> </div> <div class="paragraph"> <p>That is:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>the number of added lines;</p> </li> <li> <p>a tab;</p> </li> <li> <p>the number of deleted lines;</p> </li> <li> <p>a tab;</p> </li> <li> <p>a NUL (only exists if renamed/copied);</p> </li> <li> <p>pathname in preimage;</p> </li> <li> <p>a NUL (only exists if renamed/copied);</p> </li> <li> <p>pathname in postimage (only exists if renamed/copied);</p> </li> <li> <p>a NUL.</p> </li> </ol> </div> <div class="paragraph"> <p>The extra <code>NUL</code> before the preimage path in renamed case is to allow scripts that read the output to tell if the current record being read is a single-path record or a rename/copy record without reading ahead. After reading added and deleted lines, reading up to <code>NUL</code> would yield the pathname, but if that is <code>NUL</code>, the record will show two paths.</p> </div> </div> </div> <div class="sect1"> <h2 id="_git">GIT</h2> <div class="sectionbody"> <div class="paragraph"> <p>Part of the linkgit:git[1] suite</p> </div> </div> </div> </div> <div id="footer"> <div id="footer-text"> Last updated 2015-08-30 17:24:33 Coordinated Universal Time </div> </div> </body> </html>
bsd-2-clause
gustavoavellar/homebrew-cask
Casks/ssx.rb
371
cask :v1 => 'ssx' do version '06082006-2216' sha256 '34d904e909191e60e0b84ea43f177871ac4310c91af53e5c4cbff28c5dd29fcb' url "http://chris.schleifer.net/ssX/builds/ssX-#{version}.dmg" homepage 'http://chris.schleifer.net/ssX/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'ssX.app' end
bsd-2-clause
adamliter/homebrew-core
Formula/stress.rb
1374
class Stress < Formula desc "Tool to impose load on and stress test a computer system" homepage "https://people.seas.harvard.edu/~apw/stress/" url "https://people.seas.harvard.edu/~apw/stress/stress-1.0.4.tar.gz" mirror "https://mirrors.kernel.org/debian/pool/main/s/stress/stress_1.0.4.orig.tar.gz" sha256 "057e4fc2a7706411e1014bf172e4f94b63a12f18412378fca8684ca92408825b" bottle do cellar :any_skip_relocation sha256 "57923f0549beb3e528ad7683a09d615096d875512fb46b9ed7c54aa6382ca793" => :mojave sha256 "3087af5469f5867b82ab85158c7268d0172b58da91baec06916659bb0fd2f930" => :high_sierra sha256 "1a18d667f7804579758079e3a3f94683a64687120b5f4b77cf25a63f3f8cec39" => :sierra sha256 "b4635c185bfba65271d74aaff155161d2df388be303d135315066260e9699c5e" => :el_capitan sha256 "845f44585d0a3749c163300029f832125950d37af4a5b53c0b20fb143e6db014" => :yosemite sha256 "6741dc72df4a43cfe2c947d9e50d08df1e35029025ff2436d5a20a01117f4fb6" => :mavericks sha256 "28ac09ff04e83b174f915a6306de69f70d8b81f6316b0f1884bf2ac8061134ee" => :mountain_lion end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do system bin/"stress", "--cpu", "2", "--io", "1", "--vm", "1", "--vm-bytes", "128M", "--timeout", "1s", "--verbose" end end
bsd-2-clause
cheral/orange3
Orange/tests/test_doctest.py
2448
import sys import os from doctest import DocTestSuite, ELLIPSIS, NORMALIZE_WHITESPACE SKIP_DIRS = ( # Skip modules which import and initialize stuff that require QApplication 'Orange/widgets', 'Orange/canvas', # Skip because we don't want Orange.datasets as a module (yet) 'Orange/datasets/' ) if sys.platform == "win32": # convert to platform native path component separators SKIP_DIRS = tuple(os.path.normpath(p) for p in SKIP_DIRS) def find_modules(package): """Return a recursive list of submodules for a given package""" from os import path, walk module = path.dirname(getattr(package, '__file__', package)) parent = path.dirname(module) files = (path.join(dir, file)[len(parent) + 1:-3] for dir, dirs, files in walk(module) for file in files if file.endswith('.py')) files = (f for f in files if not f.startswith(SKIP_DIRS)) files = (f.replace(path.sep, '.') for f in files) return files class Context(dict): """ Execution context that retains the changes the tests make. Preferably use one per module to obtain nice "literate" modules that "follow along". In other words, directly the opposite of: https://docs.python.org/3/library/doctest.html#what-s-the-execution-context By popular demand: http://stackoverflow.com/questions/13106118/object-reuse-in-python-doctest/13106793#13106793 http://stackoverflow.com/questions/3286658/embedding-test-code-or-data-within-doctest-strings """ def copy(self): return self def clear(self): pass def suite(package): """Assemble test suite for doctests in path (recursively)""" from importlib import import_module for module in find_modules(package.__file__): try: module = import_module(module) yield DocTestSuite(module, globs=Context(module.__dict__.copy()), optionflags=ELLIPSIS | NORMALIZE_WHITESPACE) except ValueError: pass # No doctests in module except ImportError: import warnings warnings.warn('Unimportable module: {}'.format(module)) def load_tests(loader, tests, ignore): # This follows the load_tests protocol # https://docs.python.org/3/library/unittest.html#load-tests-protocol import Orange tests.addTests(suite(Orange)) return tests
bsd-2-clause
reelsense/homebrew-cask
Casks/icq.rb
671
cask 'icq' do version '3.0.18725' sha256 '437ce23444ae3449e53195e10b0c8a7515d8ea5357435335e4d2793c12e1f8b7' # mra.mail.ru/icq_mac3_update was verified as official when first introduced to the cask url 'https://mra.mail.ru/icq_mac3_update/icq.dmg' appcast 'https://mra.mail.ru/icq_mac3_update/icq_update.xml' name 'ICQ for macOS' homepage 'https://icq.com/mac/en' app 'ICQ.app' zap trash: [ '~/Library/Application Support/ICQ', '~/Library/Caches/com.icq.macicq', '~/Library/Preferences/com.icq.macicq.plist', '~/Library/Saved Application State/com.icq.macicq.savedState', ] end
bsd-2-clause
Chilledheart/chromium
net/url_request/url_request_context.h
8959
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This class represents contextual information (cookies, cache, etc.) // that's useful when processing resource requests. // The class is reference-counted so that it can be cleaned up after any // requests that are using it have been completed. #ifndef NET_URL_REQUEST_URL_REQUEST_CONTEXT_H_ #define NET_URL_REQUEST_URL_REQUEST_CONTEXT_H_ #include <set> #include <string> #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" #include "net/base/net_export.h" #include "net/base/request_priority.h" #include "net/http/http_network_session.h" #include "net/http/http_server_properties.h" #include "net/http/transport_security_state.h" #include "net/log/net_log.h" #include "net/ssl/ssl_config_service.h" #include "net/url_request/url_request.h" namespace net { class CertVerifier; class ChannelIDService; class CookieStore; class CTVerifier; class HostResolver; class HttpAuthHandlerFactory; class HttpTransactionFactory; class HttpUserAgentSettings; class NetworkDelegate; class NetworkQualityEstimator; class SdchManager; class ProxyService; class URLRequest; class URLRequestBackoffManager; class URLRequestJobFactory; class URLRequestThrottlerManager; // Subclass to provide application-specific context for URLRequest // instances. Note that URLRequestContext typically does not provide storage for // these member variables, since they may be shared. For the ones that aren't // shared, URLRequestContextStorage can be helpful in defining their storage. class NET_EXPORT URLRequestContext : NON_EXPORTED_BASE(public base::NonThreadSafe) { public: URLRequestContext(); virtual ~URLRequestContext(); // Copies the state from |other| into this context. void CopyFrom(const URLRequestContext* other); // May return nullptr if this context doesn't have an associated network // session. const HttpNetworkSession::Params* GetNetworkSessionParams() const; scoped_ptr<URLRequest> CreateRequest(const GURL& url, RequestPriority priority, URLRequest::Delegate* delegate) const; NetLog* net_log() const { return net_log_; } void set_net_log(NetLog* net_log) { net_log_ = net_log; } HostResolver* host_resolver() const { return host_resolver_; } void set_host_resolver(HostResolver* host_resolver) { host_resolver_ = host_resolver; } CertVerifier* cert_verifier() const { return cert_verifier_; } void set_cert_verifier(CertVerifier* cert_verifier) { cert_verifier_ = cert_verifier; } ChannelIDService* channel_id_service() const { return channel_id_service_; } void set_channel_id_service( ChannelIDService* channel_id_service) { channel_id_service_ = channel_id_service; } // Get the proxy service for this context. ProxyService* proxy_service() const { return proxy_service_; } void set_proxy_service(ProxyService* proxy_service) { proxy_service_ = proxy_service; } // Get the ssl config service for this context. SSLConfigService* ssl_config_service() const { return ssl_config_service_.get(); } void set_ssl_config_service(SSLConfigService* service) { ssl_config_service_ = service; } // Gets the HTTP Authentication Handler Factory for this context. // The factory is only valid for the lifetime of this URLRequestContext HttpAuthHandlerFactory* http_auth_handler_factory() const { return http_auth_handler_factory_; } void set_http_auth_handler_factory(HttpAuthHandlerFactory* factory) { http_auth_handler_factory_ = factory; } // Gets the http transaction factory for this context. HttpTransactionFactory* http_transaction_factory() const { return http_transaction_factory_; } void set_http_transaction_factory(HttpTransactionFactory* factory) { http_transaction_factory_ = factory; } void set_network_delegate(NetworkDelegate* network_delegate) { network_delegate_ = network_delegate; } NetworkDelegate* network_delegate() const { return network_delegate_; } void set_http_server_properties( const base::WeakPtr<HttpServerProperties>& http_server_properties) { http_server_properties_ = http_server_properties; } base::WeakPtr<HttpServerProperties> http_server_properties() const { return http_server_properties_; } // Gets the cookie store for this context (may be null, in which case // cookies are not stored). CookieStore* cookie_store() const { return cookie_store_.get(); } void set_cookie_store(CookieStore* cookie_store); TransportSecurityState* transport_security_state() const { return transport_security_state_; } void set_transport_security_state( TransportSecurityState* state) { transport_security_state_ = state; } CTVerifier* cert_transparency_verifier() const { return cert_transparency_verifier_; } void set_cert_transparency_verifier(CTVerifier* verifier) { cert_transparency_verifier_ = verifier; } const URLRequestJobFactory* job_factory() const { return job_factory_; } void set_job_factory(const URLRequestJobFactory* job_factory) { job_factory_ = job_factory; } // May return nullptr. URLRequestThrottlerManager* throttler_manager() const { return throttler_manager_; } void set_throttler_manager(URLRequestThrottlerManager* throttler_manager) { throttler_manager_ = throttler_manager; } // May return nullptr. URLRequestBackoffManager* backoff_manager() const { return backoff_manager_; } void set_backoff_manager(URLRequestBackoffManager* backoff_manager) { backoff_manager_ = backoff_manager; } // May return nullptr. SdchManager* sdch_manager() const { return sdch_manager_; } void set_sdch_manager(SdchManager* sdch_manager) { sdch_manager_ = sdch_manager; } // Gets the URLRequest objects that hold a reference to this // URLRequestContext. std::set<const URLRequest*>* url_requests() const { return url_requests_.get(); } // CHECKs that no URLRequests using this context remain. Subclasses should // additionally call AssertNoURLRequests() within their own destructor, // prior to implicit destruction of subclass-owned state. void AssertNoURLRequests() const; // Get the underlying |HttpUserAgentSettings| implementation that provides // the HTTP Accept-Language and User-Agent header values. const HttpUserAgentSettings* http_user_agent_settings() const { return http_user_agent_settings_; } void set_http_user_agent_settings( HttpUserAgentSettings* http_user_agent_settings) { http_user_agent_settings_ = http_user_agent_settings; } // Gets the NetworkQualityEstimator associated with this context. // May return nullptr. NetworkQualityEstimator* network_quality_estimator() const { return network_quality_estimator_; } void set_network_quality_estimator( NetworkQualityEstimator* network_quality_estimator) { network_quality_estimator_ = network_quality_estimator; } private: // --------------------------------------------------------------------------- // Important: When adding any new members below, consider whether they need to // be added to CopyFrom. // --------------------------------------------------------------------------- // Ownership for these members are not defined here. Clients should either // provide storage elsewhere or have a subclass take ownership. NetLog* net_log_; HostResolver* host_resolver_; CertVerifier* cert_verifier_; ChannelIDService* channel_id_service_; HttpAuthHandlerFactory* http_auth_handler_factory_; ProxyService* proxy_service_; scoped_refptr<SSLConfigService> ssl_config_service_; NetworkDelegate* network_delegate_; base::WeakPtr<HttpServerProperties> http_server_properties_; HttpUserAgentSettings* http_user_agent_settings_; scoped_refptr<CookieStore> cookie_store_; TransportSecurityState* transport_security_state_; CTVerifier* cert_transparency_verifier_; HttpTransactionFactory* http_transaction_factory_; const URLRequestJobFactory* job_factory_; URLRequestThrottlerManager* throttler_manager_; URLRequestBackoffManager* backoff_manager_; SdchManager* sdch_manager_; NetworkQualityEstimator* network_quality_estimator_; // --------------------------------------------------------------------------- // Important: When adding any new members below, consider whether they need to // be added to CopyFrom. // --------------------------------------------------------------------------- scoped_ptr<std::set<const URLRequest*> > url_requests_; DISALLOW_COPY_AND_ASSIGN(URLRequestContext); }; } // namespace net #endif // NET_URL_REQUEST_URL_REQUEST_CONTEXT_H_
bsd-3-clause
cuidingfeng/quantum
node_modules/yog2-kernel/node_modules/node-ral/node_modules/urlencode/History.md
625
0.2.0 / 2014-04-25 ================== * urlencode.stringify done (@alsotang) 0.1.2 / 2014-04-09 ================== * remove unused variable QueryString (@azbykov) 0.1.1 / 2014-02-25 ================== * improve parse() performance 10x 0.1.0 / 2014-02-24 ================== * decode with charset * add npm image * remove 0.6 for travis * update to support coveralls * use jscover instead of jscoverage * update gitignore * Merge pull request #1 from aleafs/master * Add http entries test case 0.0.1 / 2012-10-31 ================== * encode() done. add benchmark and tests * Initial commit
bsd-3-clause
meego-tablet-ux/meego-app-browser
tools/grit/grit/gather/admin_template.py
2488
#!/usr/bin/python2.4 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Gatherer for administrative template files. ''' import re import types from grit.gather import regexp from grit import exception from grit import tclib from grit import util class MalformedAdminTemplateException(exception.Base): '''This file doesn't look like a .adm file to me.''' def __init__(self, msg=''): exception.Base.__init__(self, msg) class AdmGatherer(regexp.RegexpGatherer): '''Gatherer for the translateable portions of an admin template. This gatherer currently makes the following assumptions: - there is only one [strings] section and it is always the last section of the file - translateable strings do not need to be escaped. ''' # Finds the strings section as the group named 'strings' _STRINGS_SECTION = re.compile('(?P<first_part>.+^\[strings\])(?P<strings>.+)\Z', re.MULTILINE | re.DOTALL) # Finds the translateable sections from within the [strings] section. _TRANSLATEABLES = re.compile('^\s*[A-Za-z0-9_]+\s*=\s*"(?P<text>.+)"\s*$', re.MULTILINE) def __init__(self, text): regexp.RegexpGatherer.__init__(self, text) def Escape(self, text): return text.replace('\n', '\\n') def UnEscape(self, text): return text.replace('\\n', '\n') def Parse(self): if self.have_parsed_: return m = self._STRINGS_SECTION.match(self.text_) if not m: raise MalformedAdminTemplateException() # Add the first part, which is all nontranslateable, to the skeleton self._AddNontranslateableChunk(m.group('first_part')) # Then parse the rest using the _TRANSLATEABLES regexp. self._RegExpParse(self._TRANSLATEABLES, m.group('strings')) # static method def FromFile(adm_file, ext_key=None, encoding='cp1252'): '''Loads the contents of 'adm_file' in encoding 'encoding' and creates an AdmGatherer instance that gathers from those contents. The 'ext_key' parameter is ignored. Args: adm_file: file('bingo.rc') | 'filename.rc' encoding: 'utf-8' Return: AdmGatherer(contents_of_file) ''' if isinstance(adm_file, types.StringTypes): adm_file = util.WrapInputStream(file(adm_file, 'r'), encoding) return AdmGatherer(adm_file.read()) FromFile = staticmethod(FromFile)
bsd-3-clause
deft-code/go
src/runtime/export_test.go
3299
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Export guts for testing. package runtime import ( "runtime/internal/atomic" "runtime/internal/sys" "unsafe" ) var Fadd64 = fadd64 var Fsub64 = fsub64 var Fmul64 = fmul64 var Fdiv64 = fdiv64 var F64to32 = f64to32 var F32to64 = f32to64 var Fcmp64 = fcmp64 var Fintto64 = fintto64 var F64toint = f64toint var Sqrt = sqrt var Entersyscall = entersyscall var Exitsyscall = exitsyscall var LockedOSThread = lockedOSThread var Xadduintptr = atomic.Xadduintptr var FuncPC = funcPC var Fastlog2 = fastlog2 type LFNode struct { Next uint64 Pushcnt uintptr } func LFStackPush(head *uint64, node *LFNode) { lfstackpush(head, (*lfnode)(unsafe.Pointer(node))) } func LFStackPop(head *uint64) *LFNode { return (*LFNode)(unsafe.Pointer(lfstackpop(head))) } type ParFor struct { body func(*ParFor, uint32) done uint32 Nthr uint32 thrseq uint32 Cnt uint32 wait bool } func NewParFor(nthrmax uint32) *ParFor { var desc *ParFor systemstack(func() { desc = (*ParFor)(unsafe.Pointer(parforalloc(nthrmax))) }) return desc } func ParForSetup(desc *ParFor, nthr, n uint32, wait bool, body func(*ParFor, uint32)) { systemstack(func() { parforsetup((*parfor)(unsafe.Pointer(desc)), nthr, n, wait, *(*func(*parfor, uint32))(unsafe.Pointer(&body))) }) } func ParForDo(desc *ParFor) { systemstack(func() { parfordo((*parfor)(unsafe.Pointer(desc))) }) } func ParForIters(desc *ParFor, tid uint32) (uint32, uint32) { desc1 := (*parfor)(unsafe.Pointer(desc)) pos := desc1.thr[tid].pos return uint32(pos), uint32(pos >> 32) } func GCMask(x interface{}) (ret []byte) { systemstack(func() { ret = getgcmask(x) }) return } func RunSchedLocalQueueTest() { testSchedLocalQueue() } func RunSchedLocalQueueStealTest() { testSchedLocalQueueSteal() } var StringHash = stringHash var BytesHash = bytesHash var Int32Hash = int32Hash var Int64Hash = int64Hash var EfaceHash = efaceHash var IfaceHash = ifaceHash var MemclrBytes = memclrBytes var HashLoad = &hashLoad // entry point for testing func GostringW(w []uint16) (s string) { systemstack(func() { s = gostringw(&w[0]) }) return } var Gostringnocopy = gostringnocopy var Maxstring = &maxstring type Uintreg sys.Uintreg var Open = open var Close = closefd var Read = read var Write = write func Envs() []string { return envs } func SetEnvs(e []string) { envs = e } var BigEndian = sys.BigEndian // For benchmarking. func BenchSetType(n int, x interface{}) { e := *efaceOf(&x) t := e._type var size uintptr var p unsafe.Pointer switch t.kind & kindMask { case kindPtr: t = (*ptrtype)(unsafe.Pointer(t)).elem size = t.size p = e.data case kindSlice: slice := *(*struct { ptr unsafe.Pointer len, cap uintptr })(e.data) t = (*slicetype)(unsafe.Pointer(t)).elem size = t.size * slice.len p = slice.ptr } allocSize := roundupsize(size) systemstack(func() { for i := 0; i < n; i++ { heapBitsSetType(uintptr(p), allocSize, size, t) } }) } const PtrSize = sys.PtrSize var TestingAssertE2I2GC = &testingAssertE2I2GC var TestingAssertE2T2GC = &testingAssertE2T2GC var ForceGCPeriod = &forcegcperiod
bsd-3-clause
nagyistoce/devide
modules/vtk_basic/vtkSynchronizedTemplatesCutter3D.py
520
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkSynchronizedTemplatesCutter3D(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkSynchronizedTemplatesCutter3D(), 'Processing.', ('vtkImageData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
bsd-3-clause
forste/haReFork
tools/base/transforms/tests/1.hs
37
module A where ~(Just x) = Nothing
bsd-3-clause
giserh/userguide
feature-engineering/tfidf.md
4680
#TF-IDF The prototypical application of TF-IDF transformations involves document collections, where each element represents a document in bag-of-words format, i.e. a dictionary whose keys are words and whose values are the number of times the word occurs in the document. For more details, check the reference section for further reading. The TF-IDF transformation performs the following computation $$ \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) $$ where $$tf(w, d)$$ is the number of times word $$w$$ appeared in document $$d$$, $$f(w)$$ is the number of documents word $$w$$ appeared in, $$N$$ is the number of documents, and we use the natural logarithm. The transformed output is a column of type dictionary (`max_categories` per column dimension sparse vector) where the key corresponds to the index of the categorical variable and the value is `1`. The behavior of TF-IDF for each input data column type for supported types is as follows. - dict: Each (key, value) pair is treated as count associated with the key for this row. A common example is to have a dict element contain a bag-of-words representation of a document, where each key is a word and each value is the number of times that word occurs in the document. All non-numeric values are ignored. - list: The list is converted to bag of words of format, where the keys are the unique elements in the list and the values are the counts of those unique elements. After this step, the behaviour is identical to dict. - string: Behaves identically to a **dict**, where the dictionary is generated by converting the string into a bag-of-words format. For example, 'I really like really fluffy dogs' would get converted to {'I' : 1, 'really': 2, 'like': 1, 'fluffy': 1, 'dogs':1}. #### Introductory Example ```python import graphlab as gl # Create data. sf = gl.SFrame({'a': ['1','2','3'], 'b' : [2,3,4]}) # Create a one-hot encoder. from graphlab.toolkits.feature_engineering import TFIDF encoder = gl.feature_engineering.create(sf, TFIDF('a')) # Transform the data. transformed_sf = encoder.transform(sf) ``` ```no-highlight Columns: a dict b int Rows: 3 Data: +---------------------------+---+ | a | b | +---------------------------+---+ | {'1': 1.0986122886681098} | 2 | | {'2': 1.0986122886681098} | 3 | | {'3': 1.0986122886681098} | 4 | +---------------------------+---+ [3 rows x 2 columns] ``` ```python # Save the transformer. >>> encoder.save('save-path') # Return the indices in the encoding. >>> encoder['document_frequencies'] ``` ```no-highlight Columns: feature_column str term str document_frequency str Rows: 3 Data: +----------------+------+--------------------+ | feature_column | term | document_frequency | +----------------+------+--------------------+ | a | 1 | 1 | | a | 2 | 1 | | a | 3 | 1 | +----------------+------+--------------------+ [3 rows x 3 columns] ``` #### Fitting and Transforming ```python # For list columns: l1 = ['a','good','example'] l2 = ['a','better','example'] sf = gl.SFrame({'a' : [l1,l2]}) tfidf = gl.feature_engineering.TFIDF('a') fit_tfidf = tfidf.fit(sf) transformed_sf = fit_tfidf.transform(sf) ``` ```no-highlight Columns: a dict Rows: 2 Data: +-------------------------------+ | a | +-------------------------------+ | {'a': 0.0, 'good': 0.69314... | | {'better': 0.6931471805599... | +-------------------------------+ [2 rows x 1 columns] ``` ```python # For string columns: sf = gl.SFrame({'a' : ['a good example', 'a better example']}) tfidf = gl.feature_engineering.TFIDF('a') fit_tfidf = tfidf.fit(sf) transformed_sf = fit_tfidf.transform(sf) ``` ```no-highlight Columns: a dict Rows: 2 Data: +-------------------------------+ | a | +-------------------------------+ | {'a': 0.0, 'good': 0.69314... | | {'better': 0.6931471805599... | +-------------------------------+ [2 rows x 1 columns] ``` ```python # For dictionary columns: sf = gl.SFrame( {'docs': [{'this': 1, 'is': 1, 'a': 2, 'sample': 1}, {'this': 1, 'is': 1, 'another': 2, 'example': 3}]}) tfidf = gl.feature_engineering.TFIDF('docs') fit_tfidf = tfidf.fit(sf) transformed_sf = fit_tfidf.transform(sf) ``` ```no-highlight Columns: docs dict Rows: 2 Data: +-------------------------------+ | docs | +-------------------------------+ | {'this': 0.0, 'a': 1.38629... | | {'this': 0.0, 'is': 0.0, '... | +-------------------------------+ [2 rows x 1 columns] ```
bsd-3-clause
szdavid92/actor-framework
libcaf_core/caf/response_promise.hpp
2848
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_RESPONSE_PROMISE_HPP #define CAF_RESPONSE_PROMISE_HPP #include "caf/actor.hpp" #include "caf/message.hpp" #include "caf/actor_addr.hpp" #include "caf/message_id.hpp" namespace caf { /// A response promise can be used to deliver a uniquely identifiable /// response message from the server (i.e. receiver of the request) /// to the client (i.e. the sender of the request). class response_promise { public: response_promise() = default; response_promise(response_promise&&) = default; response_promise(const response_promise&) = default; response_promise& operator=(response_promise&&) = default; response_promise& operator=(const response_promise&) = default; response_promise(const actor_addr& from, const actor_addr& to, const message_id& response_id); /// Queries whether this promise is still valid, i.e., no response /// was yet delivered to the client. inline explicit operator bool() const { // handle is valid if it has a receiver return static_cast<bool>(to_); } /// Sends `response_message` and invalidates this handle afterwards. template <class... Ts> void deliver(Ts&&... xs) const { deliver_impl(make_message(std::forward<Ts>(xs)...)); } private: void deliver_impl(message response_message) const; actor_addr from_; actor_addr to_; message_id id_; }; } // namespace caf #endif // CAF_RESPONSE_PROMISE_HPP
bsd-3-clause
espadrine/opera
chromium/src/chrome/browser/ui/gtk/importer/import_lock_dialog_gtk.cc
2625
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/gtk/importer/import_lock_dialog_gtk.h" #include <gtk/gtk.h> #include "base/bind.h" #include "base/message_loop.h" #include "chrome/browser/importer/importer_lock_dialog.h" #include "chrome/browser/ui/gtk/gtk_util.h" #include "content/public/browser/user_metrics.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/gtk/gtk_hig_constants.h" #include "ui/base/l10n/l10n_util.h" using content::UserMetricsAction; namespace importer { void ShowImportLockDialog(gfx::NativeWindow parent, const base::Callback<void(bool)>& callback) { ImportLockDialogGtk::Show(parent, callback); content::RecordAction(UserMetricsAction("ImportLockDialogGtk_Shown")); } } // namespace importer // static void ImportLockDialogGtk::Show(GtkWindow* parent, const base::Callback<void(bool)>& callback) { new ImportLockDialogGtk(parent, callback); } ImportLockDialogGtk::ImportLockDialogGtk( GtkWindow* parent, const base::Callback<void(bool)>& callback) : callback_(callback) { // Build the dialog. dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_IMPORTER_LOCK_TITLE).c_str(), parent, (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), NULL); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_IMPORTER_LOCK_CANCEL).c_str(), GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_IMPORTER_LOCK_OK).c_str(), GTK_STOCK_OK, GTK_RESPONSE_ACCEPT); GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog_)); gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing); GtkWidget* label = gtk_label_new( l10n_util::GetStringUTF8(IDS_IMPORTER_LOCK_TEXT).c_str()); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE); gtk_widget_show_all(dialog_); } ImportLockDialogGtk::~ImportLockDialogGtk() {} void ImportLockDialogGtk::OnResponse(GtkWidget* dialog, int response_id) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(callback_, response_id == GTK_RESPONSE_ACCEPT)); gtk_widget_destroy(dialog_); delete this; }
bsd-3-clause
mxOBS/deb-pkg_trusty_chromium-browser
third_party/WebKit/Source/core/editing/ApplyStyleCommand.h
8182
/* * Copyright (C) 2005, 2006, 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ApplyStyleCommand_h #define ApplyStyleCommand_h #include "core/editing/CompositeEditCommand.h" #include "core/editing/WritingDirection.h" #include "core/html/HTMLElement.h" namespace blink { class EditingStyle; class HTMLSpanElement; class StyleChange; enum ShouldIncludeTypingStyle { IncludeTypingStyle, IgnoreTypingStyle }; class ApplyStyleCommand final : public CompositeEditCommand { public: enum EPropertyLevel { PropertyDefault, ForceBlockProperties }; enum InlineStyleRemovalMode { RemoveIfNeeded, RemoveAlways, RemoveNone }; enum EAddStyledElement { AddStyledElement, DoNotAddStyledElement }; typedef bool (*IsInlineElementToRemoveFunction)(const Element*); static PassRefPtrWillBeRawPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault) { return adoptRefWillBeNoop(new ApplyStyleCommand(document, style, action, level)); } static PassRefPtrWillBeRawPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, const Position& start, const Position& end, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault) { return adoptRefWillBeNoop(new ApplyStyleCommand(document, style, start, end, action, level)); } static PassRefPtrWillBeRawPtr<ApplyStyleCommand> create(PassRefPtrWillBeRawPtr<Element> element, bool removeOnly = false, EditAction action = EditActionChangeAttributes) { return adoptRefWillBeNoop(new ApplyStyleCommand(element, removeOnly, action)); } static PassRefPtrWillBeRawPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction action = EditActionChangeAttributes) { return adoptRefWillBeNoop(new ApplyStyleCommand(document, style, isInlineElementToRemoveFunction, action)); } virtual void trace(Visitor*) override; private: ApplyStyleCommand(Document&, const EditingStyle*, EditAction, EPropertyLevel); ApplyStyleCommand(Document&, const EditingStyle*, const Position& start, const Position& end, EditAction, EPropertyLevel); ApplyStyleCommand(PassRefPtrWillBeRawPtr<Element>, bool removeOnly, EditAction); ApplyStyleCommand(Document&, const EditingStyle*, bool (*isInlineElementToRemove)(const Element*), EditAction); virtual void doApply() override; virtual EditAction editingAction() const override; // style-removal helpers bool isStyledInlineElementToRemove(Element*) const; bool shouldApplyInlineStyleToRun(EditingStyle*, Node* runStart, Node* pastEndNode); void removeConflictingInlineStyleFromRun(EditingStyle*, RefPtrWillBeMember<Node>& runStart, RefPtrWillBeMember<Node>& runEnd, PassRefPtrWillBeRawPtr<Node> pastEndNode); bool removeInlineStyleFromElement(EditingStyle*, PassRefPtrWillBeRawPtr<HTMLElement>, InlineStyleRemovalMode = RemoveIfNeeded, EditingStyle* extractedStyle = nullptr); inline bool shouldRemoveInlineStyleFromElement(EditingStyle* style, HTMLElement* element) {return removeInlineStyleFromElement(style, element, RemoveNone);} void replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement*); bool removeImplicitlyStyledElement(EditingStyle*, HTMLElement*, InlineStyleRemovalMode, EditingStyle* extractedStyle); bool removeCSSStyle(EditingStyle*, HTMLElement*, InlineStyleRemovalMode = RemoveIfNeeded, EditingStyle* extractedStyle = nullptr); HTMLElement* highestAncestorWithConflictingInlineStyle(EditingStyle*, Node*); void applyInlineStyleToPushDown(Node*, EditingStyle*); void pushDownInlineStyleAroundNode(EditingStyle*, Node*); void removeInlineStyle(EditingStyle* , const Position& start, const Position& end); bool elementFullySelected(HTMLElement&, const Position& start, const Position& end) const; // style-application helpers void applyBlockStyle(EditingStyle*); void applyRelativeFontStyleChange(EditingStyle*); void applyInlineStyle(EditingStyle*); void fixRangeAndApplyInlineStyle(EditingStyle*, const Position& start, const Position& end); void applyInlineStyleToNodeRange(EditingStyle*, PassRefPtrWillBeRawPtr<Node> startNode, PassRefPtrWillBeRawPtr<Node> pastEndNode); void addBlockStyle(const StyleChange&, HTMLElement*); void addInlineStyleIfNeeded(EditingStyle*, PassRefPtrWillBeRawPtr<Node> start, PassRefPtrWillBeRawPtr<Node> end, EAddStyledElement = AddStyledElement); Position positionToComputeInlineStyleChange(PassRefPtrWillBeRawPtr<Node>, RefPtrWillBeMember<HTMLSpanElement>& dummyElement); void applyInlineStyleChange(PassRefPtrWillBeRawPtr<Node> startNode, PassRefPtrWillBeRawPtr<Node> endNode, StyleChange&, EAddStyledElement); void splitTextAtStart(const Position& start, const Position& end); void splitTextAtEnd(const Position& start, const Position& end); void splitTextElementAtStart(const Position& start, const Position& end); void splitTextElementAtEnd(const Position& start, const Position& end); bool shouldSplitTextElement(Element*, EditingStyle*); bool isValidCaretPositionInTextNode(const Position& position); bool mergeStartWithPreviousIfIdentical(const Position& start, const Position& end); bool mergeEndWithNextIfIdentical(const Position& start, const Position& end); void cleanupUnstyledAppleStyleSpans(ContainerNode* dummySpanAncestor); void surroundNodeRangeWithElement(PassRefPtrWillBeRawPtr<Node> start, PassRefPtrWillBeRawPtr<Node> end, PassRefPtrWillBeRawPtr<Element>); float computedFontSize(Node*); void joinChildTextNodes(ContainerNode*, const Position& start, const Position& end); HTMLElement* splitAncestorsWithUnicodeBidi(Node*, bool before, WritingDirection allowedDirection); void removeEmbeddingUpToEnclosingBlock(Node*, HTMLElement* unsplitAncestor); void updateStartEnd(const Position& newStart, const Position& newEnd); Position startPosition(); Position endPosition(); RefPtrWillBeMember<EditingStyle> m_style; EditAction m_editingAction; EPropertyLevel m_propertyLevel; Position m_start; Position m_end; bool m_useEndingSelection; RefPtrWillBeMember<Element> m_styledInlineElement; bool m_removeOnly; IsInlineElementToRemoveFunction m_isInlineElementToRemoveFunction; }; enum ShouldStyleAttributeBeEmpty { AllowNonEmptyStyleAttribute, StyleAttributeShouldBeEmpty }; bool isEmptyFontTag(const Element*, ShouldStyleAttributeBeEmpty = StyleAttributeShouldBeEmpty); bool isLegacyAppleHTMLSpanElement(const Node*); bool isStyleSpanOrSpanWithOnlyStyleAttribute(const Element*); PassRefPtrWillBeRawPtr<HTMLSpanElement> createStyleSpanElement(Document&); } // namespace blink #endif
bsd-3-clause
princeofdarkness76/gfxCardStatus
gfx playground/Pods/ReactiveCocoa/ReactiveCocoaFramework/ReactiveCocoa/NSControl+RACTextSignalSupport.h
561
// // NSControl+RACTextSignalSupport.h // ReactiveCocoa // // Created by Justin Spahr-Summers on 2013-03-08. // Copyright (c) 2013 GitHub, Inc. All rights reserved. // #import <Cocoa/Cocoa.h> @class RACSignal; @interface NSControl (RACTextSignalSupport) // Observes a text-based control for changes. // // Using this method on a control without editable text is considered undefined // behavior. // // Returns a signal which sends the current string value of the receiver, then // the new value any time it changes. - (RACSignal *)rac_textSignal; @end
bsd-3-clause
simonegli8/Websitepanel
WebsitePanel/Sources/WebsitePanel.Providers.FTP.IIs70/Configuration/PermissionsFlags.cs
1852
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace WebsitePanel.Providers.FTP.IIs70.Config { using System; [Flags] public enum PermissionsFlags { Read = 1, Write = 2 } }
bsd-3-clause
Firehed/phpunit
tests/_files/VariousDocblockDefinedDataProvider.php
1404
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\TestFixture; final class VariousDocblockDefinedDataProvider { /** * @anotherAnnotation */ public function anotherAnnotation(): void { } /** * @testWith [1] */ public function testWith1(): void { } /** * @testWith [1, 2] * [3, 4] */ public function testWith1234(): void { } /** * @testWith ["ab"] * [true] * [null] */ public function testWithABTrueNull(): void { } /** * @testWith [1] * [2] * @annotation */ public function testWith12AndAnotherAnnotation(): void { } /** * @testWith [1] * [2] * blah blah */ public function testWith12AndBlahBlah(): void { } /** * @testWith ["\"", "\""] */ public function testWithEscapedString(): void { } /** * @testWith [s] */ public function testWithMalformedValue(): void { } /** * @testWith ["valid"] * [invalid] */ public function testWithWellFormedAndMalformedValue(): void { } }
bsd-3-clause
vitalyster/libcommuni-gbp
src/core/ircconnection.cpp
52766
/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ircconnection.h" #include "ircconnection_p.h" #include "ircnetwork_p.h" #include "irccommand_p.h" #include "ircprotocol.h" #include "ircnetwork.h" #include "irccommand.h" #include "ircmessage.h" #include "ircdebug_p.h" #include "ircfilter.h" #include "irc.h" #include <QLocale> #include <QRegExp> #include <QDateTime> #include <QTcpSocket> #include <QTextCodec> #include <QMetaObject> #include <QMetaMethod> #include <QMetaEnum> #ifndef QT_NO_SSL #include <QSslSocket> #include <QSslError> #endif // QT_NO_SSL #include <QDataStream> #include <QVariantMap> IRC_BEGIN_NAMESPACE /*! \file ircconnection.h \brief \#include &lt;IrcConnection&gt; */ /*! \class IrcConnection ircconnection.h IrcConnection \ingroup core \brief Provides means to establish a connection to an IRC server. \section connection-management Connection management Before \ref open() "opening" a connection, it must be first initialized with \ref host, \ref userName, \ref nickName and \ref realName. The connection status may be queried at any time via status(). Also \ref active "isActive()" and \ref connected "isConnected()" are provided for convenience. In addition to the \ref status "statusChanged()" signal, the most important statuses are informed via the following convenience signals: \li connecting() - The connection is being established. \li \ref connected "connected()" - The IRC connection has been established, and the server is ready to receive commands. \li disconnected() - The connection has been lost. \section receiving-messages Receiving messages Whenever a message is received from the server, the messageReceived() signal is emitted. Also message type specific signals are provided for convenience. See messageReceived() and IrcMessage and its subclasses for more details. \section sending-commands Sending commands Sending commands to a server is most conveniently done by creating them via the various static \ref IrcCommand "IrcCommand::createXxx()" methods and passing them to sendCommand(). Also sendData() is provided for more low-level access. See IrcCommand for more details. \section example Example \code IrcConnection* connection = new IrcConnection(this); connect(connection, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*))); connection->setHost("irc.server.com"); connection->setUserName("me"); connection->setNickName("myself"); connection->setRealName("And I"); connection->sendCommand(IrcCommand::createJoin("#mine")); connection->open(); \endcode \sa IrcNetwork, IrcMessage, IrcCommand */ /*! \enum IrcConnection::Status This enum describes the connection status. */ /*! \var IrcConnection::Inactive \brief The connection is inactive. */ /*! \var IrcConnection::Waiting \brief The connection is waiting for a reconnect. */ /*! \var IrcConnection::Connecting \brief The connection is being established. */ /*! \var IrcConnection::Connected \brief The connection has been established. */ /*! \var IrcConnection::Closing \brief The connection is being closed. */ /*! \var IrcConnection::Closed \brief The connection has been closed. */ /*! \var IrcConnection::Error \brief The connection has encountered an error. */ /*! \fn void IrcConnection::connecting() This signal is emitted when the connection is being established. The underlying \ref socket has connected, but the IRC handshake is not yet finished and the server is not yet ready to receive commands. */ /*! \fn void IrcConnection::nickNameRequired(const QString& reserved, QString* alternate) This signal is emitted when the requested nick name is \a reserved and an \a alternate nick name should be provided. An alternate nick name may be set via the provided argument, by changing the \ref nickName property, or by sending a nick command directly. \sa nickNames, IrcCommand::createNick(), Irc::ERR_NICKNAMEINUSE, Irc::ERR_NICKCOLLISION */ /*! \fn void IrcConnection::channelKeyRequired(const QString& channel, QString* key) This signal is emitted when joining a \a channel requires a \a key. The key may be set via the provided argument, or by sending a new join command directly. \sa IrcCommand::createJoin(), Irc::ERR_BADCHANNELKEY */ /*! \fn void IrcConnection::disconnected() This signal is emitted when the connection has been lost. */ /*! \fn void IrcConnection::socketError(QAbstractSocket::SocketError error) This signal is emitted when a \ref socket \a error occurs. \sa QAbstractSocket::error() */ /*! \fn void IrcConnection::socketStateChanged(QAbstractSocket::SocketState state) This signal is emitted when the \a state of the underlying \ref socket changes. \sa QAbstractSocket::stateChanged() */ /*! \since 3.2 \fn void IrcConnection::secureError() This signal is emitted when SSL socket error occurs. Either QSslSocket::sslErrors() was emitted, or the handshake failed meaning that the server is not SSL-enabled. */ /*! \fn void IrcConnection::messageReceived(IrcMessage* message) This signal is emitted when a \a message is received. In addition, message type specific signals are provided for convenience: \li void <b>accountMessageReceived</b>(\ref IrcAccountMessage* message) (\b since 3.3) \li void <b>awayMessageReceived</b>(\ref IrcAwayMessage* message) (\b since 3.3) \li void <b>batchMessageReceived</b>(\ref IrcBatchMessage* message) (\b since 3.5) \li void <b>capabilityMessageReceived</b>(\ref IrcCapabilityMessage* message) \li void <b>errorMessageReceived</b>(\ref IrcErrorMessage* message) \li void <b>hostChangeMessageReceived</b>(\ref IrcHostChangeMessage* message) (\b since 3.4) \li void <b>inviteMessageReceived</b>(\ref IrcInviteMessage* message) \li void <b>joinMessageReceived</b>(\ref IrcJoinMessage* message) \li void <b>kickMessageReceived</b>(\ref IrcKickMessage* message) \li void <b>modeMessageReceived</b>(\ref IrcModeMessage* message) \li void <b>motdMessageReceived</b>(\ref IrcMotdMessage* message) \li void <b>namesMessageReceived</b>(\ref IrcNamesMessage* message) \li void <b>nickMessageReceived</b>(\ref IrcNickMessage* message) \li void <b>noticeMessageReceived</b>(\ref IrcNoticeMessage* message) \li void <b>numericMessageReceived</b>(\ref IrcNumericMessage* message) \li void <b>partMessageReceived</b>(\ref IrcPartMessage* message) \li void <b>pingMessageReceived</b>(\ref IrcPingMessage* message) \li void <b>pongMessageReceived</b>(\ref IrcPongMessage* message) \li void <b>privateMessageReceived</b>(\ref IrcPrivateMessage* message) \li void <b>quitMessageReceived</b>(\ref IrcQuitMessage* message) \li void <b>topicMessageReceived</b>(\ref IrcTopicMessage* message) \li void <b>whoisMessageReceived</b>(\ref IrcWhoisMessage* message) (\b since 3.3) \li void <b>whowasMessageReceived</b>(\ref IrcWhowasMessage* message) (\b since 3.3) \li void <b>whoReplyMessageReceived</b>(\ref IrcWhoReplyMessage* message) (\b since 3.1) */ #ifndef IRC_DOXYGEN IrcConnectionPrivate::IrcConnectionPrivate() : q_ptr(0), encoding("ISO-8859-15"), network(0), protocol(0), socket(0), host(), port(6667), currentServer(-1), userName(), nickName(), realName(), enabled(true), status(IrcConnection::Inactive), pendingOpen(false), closed(false) { } void IrcConnectionPrivate::init(IrcConnection* connection) { q_ptr = connection; network = IrcNetworkPrivate::create(connection); connection->setSocket(new QTcpSocket(connection)); connection->setProtocol(new IrcProtocol(connection)); QObject::connect(&reconnecter, SIGNAL(timeout()), connection, SLOT(_irc_reconnect())); } void IrcConnectionPrivate::_irc_connected() { Q_Q(IrcConnection); closed = false; pendingOpen = false; emit q->connecting(); if (q->isSecure()) QMetaObject::invokeMethod(socket, "startClientEncryption"); protocol->open(); } void IrcConnectionPrivate::_irc_disconnected() { Q_Q(IrcConnection); protocol->close(); emit q->disconnected(); reconnect(); } void IrcConnectionPrivate::_irc_error(QAbstractSocket::SocketError error) { Q_Q(IrcConnection); if (error == QAbstractSocket::SslHandshakeFailedError) { ircDebug(q, IrcDebug::Error) << error; setStatus(IrcConnection::Error); emit q->secureError(); } else if (!closed || (error != QAbstractSocket::RemoteHostClosedError && error != QAbstractSocket::UnknownSocketError)) { ircDebug(q, IrcDebug::Error) << error; emit q->socketError(error); setStatus(IrcConnection::Error); reconnect(); } } void IrcConnectionPrivate::_irc_sslErrors() { Q_Q(IrcConnection); QStringList errors; #ifndef QT_NO_SSL QSslSocket* ssl = qobject_cast<QSslSocket*>(socket); if (ssl) { foreach (const QSslError& error, ssl->sslErrors()) errors += error.errorString(); } #endif ircDebug(q, IrcDebug::Error) << errors; emit q->secureError(); } void IrcConnectionPrivate::_irc_state(QAbstractSocket::SocketState state) { Q_Q(IrcConnection); switch (state) { case QAbstractSocket::UnconnectedState: if (closed) setStatus(IrcConnection::Closed); break; case QAbstractSocket::ClosingState: if (status != IrcConnection::Error && status != IrcConnection::Waiting) setStatus(IrcConnection::Closing); break; case QAbstractSocket::HostLookupState: case QAbstractSocket::ConnectingState: case QAbstractSocket::ConnectedState: default: setStatus(IrcConnection::Connecting); break; } emit q->socketStateChanged(state); } void IrcConnectionPrivate::_irc_reconnect() { Q_Q(IrcConnection); if (!q->isActive()) { reconnecter.stop(); q->open(); } } void IrcConnectionPrivate::_irc_readData() { protocol->read(); } void IrcConnectionPrivate::_irc_filterDestroyed(QObject* filter) { messageFilters.removeAll(filter); commandFilters.removeAll(filter); } static bool parseServer(const QString& server, QString* host, int* port, bool* ssl) { QStringList p = server.split(QRegExp("[: ]"), QString::SkipEmptyParts); *host = p.value(0); *ssl = p.value(1).startsWith(QLatin1Char('+')); bool ok = false; *port = p.value(1).toInt(&ok); if (*port == 0) *port = 6667; return !host->isEmpty() && (p.value(1).isEmpty() || ok) && (p.count() == 1 || p.count() == 2); } void IrcConnectionPrivate::open() { Q_Q(IrcConnection); if (q->isActive()) { pendingOpen = true; } else { closed = false; if (!servers.isEmpty()) { QString h; int p; bool s; QString server = servers.value((++currentServer) % servers.count()); if (!parseServer(server, &h, &p, &s)) qWarning() << "IrcConnection::servers: malformed line" << server; q->setHost(h); q->setPort(p); q->setSecure(s); } socket->connectToHost(host, port); } } void IrcConnectionPrivate::reconnect() { if (enabled && (status != IrcConnection::Closed || !closed || pendingOpen) && !reconnecter.isActive() && reconnecter.interval() > 0) { pendingOpen = false; reconnecter.start(); setStatus(IrcConnection::Waiting); } } void IrcConnectionPrivate::setNick(const QString& nick) { Q_Q(IrcConnection); if (nickName != nick) { nickName = nick; emit q->nickNameChanged(nick); } } void IrcConnectionPrivate::setStatus(IrcConnection::Status value) { Q_Q(IrcConnection); if (status != value) { const bool wasConnected = q->isConnected(); status = value; emit q->statusChanged(value); if (!wasConnected && q->isConnected()) { emit q->connected(); foreach (const QByteArray& data, pendingData) q->sendRaw(data); pendingData.clear(); } ircDebug(q, IrcDebug::Status) << status << qPrintable(host) << port; } } void IrcConnectionPrivate::setInfo(const QHash<QString, QString>& info) { Q_Q(IrcConnection); const QString oldName = q->displayName(); IrcNetworkPrivate* priv = IrcNetworkPrivate::get(network); priv->setInfo(info); const QString newName = q->displayName(); if (oldName != newName) emit q->displayNameChanged(newName); } bool IrcConnectionPrivate::receiveMessage(IrcMessage* msg) { Q_Q(IrcConnection); if (msg->type() == IrcMessage::Join && msg->isOwn()) { replies.clear(); } else if (msg->type() == IrcMessage::Numeric) { int code = static_cast<IrcNumericMessage*>(msg)->code(); if (code == Irc::RPL_NAMREPLY || code == Irc::RPL_ENDOFNAMES) { if (!replies.contains(Irc::RPL_ENDOFNAMES)) msg->setFlag(IrcMessage::Implicit); } else if (code == Irc::RPL_TOPIC || code == Irc::RPL_NOTOPIC || code == Irc::RPL_TOPICWHOTIME || code == Irc::RPL_CHANNEL_URL || code == Irc::RPL_CREATIONTIME) { if (!replies.contains(code)) msg->setFlag(IrcMessage::Implicit); } replies.insert(code); } bool filtered = false; for (int i = messageFilters.count() - 1; !filtered && i >= 0; --i) { IrcMessageFilter* filter = qobject_cast<IrcMessageFilter*>(messageFilters.at(i)); if (filter) filtered |= filter->messageFilter(msg); } if (!filtered) { emit q->messageReceived(msg); switch (msg->type()) { case IrcMessage::Account: emit q->accountMessageReceived(static_cast<IrcAccountMessage*>(msg)); break; case IrcMessage::Away: emit q->awayMessageReceived(static_cast<IrcAwayMessage*>(msg)); break; case IrcMessage::Batch: emit q->batchMessageReceived(static_cast<IrcBatchMessage*>(msg)); break; case IrcMessage::Capability: emit q->capabilityMessageReceived(static_cast<IrcCapabilityMessage*>(msg)); break; case IrcMessage::Error: emit q->errorMessageReceived(static_cast<IrcErrorMessage*>(msg)); break; case IrcMessage::HostChange: emit q->hostChangeMessageReceived(static_cast<IrcHostChangeMessage*>(msg)); break; case IrcMessage::Invite: emit q->inviteMessageReceived(static_cast<IrcInviteMessage*>(msg)); break; case IrcMessage::Join: emit q->joinMessageReceived(static_cast<IrcJoinMessage*>(msg)); break; case IrcMessage::Kick: emit q->kickMessageReceived(static_cast<IrcKickMessage*>(msg)); break; case IrcMessage::Mode: emit q->modeMessageReceived(static_cast<IrcModeMessage*>(msg)); break; case IrcMessage::Motd: emit q->motdMessageReceived(static_cast<IrcMotdMessage*>(msg)); break; case IrcMessage::Names: emit q->namesMessageReceived(static_cast<IrcNamesMessage*>(msg)); break; case IrcMessage::Nick: emit q->nickMessageReceived(static_cast<IrcNickMessage*>(msg)); break; case IrcMessage::Notice: emit q->noticeMessageReceived(static_cast<IrcNoticeMessage*>(msg)); break; case IrcMessage::Numeric: emit q->numericMessageReceived(static_cast<IrcNumericMessage*>(msg)); break; case IrcMessage::Part: emit q->partMessageReceived(static_cast<IrcPartMessage*>(msg)); break; case IrcMessage::Ping: emit q->pingMessageReceived(static_cast<IrcPingMessage*>(msg)); break; case IrcMessage::Pong: emit q->pongMessageReceived(static_cast<IrcPongMessage*>(msg)); break; case IrcMessage::Private: emit q->privateMessageReceived(static_cast<IrcPrivateMessage*>(msg)); break; case IrcMessage::Quit: emit q->quitMessageReceived(static_cast<IrcQuitMessage*>(msg)); break; case IrcMessage::Topic: emit q->topicMessageReceived(static_cast<IrcTopicMessage*>(msg)); break; case IrcMessage::Whois: emit q->whoisMessageReceived(static_cast<IrcWhoisMessage*>(msg)); break; case IrcMessage::Whowas: emit q->whowasMessageReceived(static_cast<IrcWhowasMessage*>(msg)); break; case IrcMessage::WhoReply: emit q->whoReplyMessageReceived(static_cast<IrcWhoReplyMessage*>(msg)); break; case IrcMessage::Unknown: default: break; } } if (!msg->parent() || msg->parent() == q) msg->deleteLater(); return !filtered; } IrcCommand* IrcConnectionPrivate::createCtcpReply(IrcPrivateMessage* request) { Q_Q(IrcConnection); IrcCommand* reply = 0; const QMetaObject* metaObject = q->metaObject(); int idx = metaObject->indexOfMethod("createCtcpReply(QVariant)"); if (idx != -1) { // QML: QVariant createCtcpReply(QVariant) QVariant ret; QMetaMethod method = metaObject->method(idx); method.invoke(q, Q_RETURN_ARG(QVariant, ret), Q_ARG(QVariant, QVariant::fromValue(request))); reply = ret.value<IrcCommand*>(); } else { // C++: IrcCommand* createCtcpReply(IrcPrivateMessage*) idx = metaObject->indexOfMethod("createCtcpReply(IrcPrivateMessage*)"); QMetaMethod method = metaObject->method(idx); method.invoke(q, Q_RETURN_ARG(IrcCommand*, reply), Q_ARG(IrcPrivateMessage*, request)); } return reply; } #endif // IRC_DOXYGEN /*! Constructs a new IRC connection with \a parent. */ IrcConnection::IrcConnection(QObject* parent) : QObject(parent), d_ptr(new IrcConnectionPrivate) { Q_D(IrcConnection); d->init(this); } /*! Constructs a new IRC connection with \a host and \a parent. */ IrcConnection::IrcConnection(const QString& host, QObject* parent) : QObject(parent), d_ptr(new IrcConnectionPrivate) { Q_D(IrcConnection); d->init(this); setHost(host); } /*! Destructs the IRC connection. */ IrcConnection::~IrcConnection() { close(); emit destroyed(this); } /*! \since 3.4 Clones the IRC connection. */ IrcConnection* IrcConnection::clone(QObject *parent) const { IrcConnection* connection = new IrcConnection(parent); connection->setHost(host()); connection->setPort(port()); connection->setServers(servers()); connection->setUserName(userName()); connection->setNickName(nickName()); connection->setRealName(realName()); connection->setPassword(password()); connection->setNickNames(nickNames()); connection->setDisplayName(displayName()); connection->setUserData(userData()); connection->setEncoding(encoding()); connection->setEnabled(isEnabled()); connection->setReconnectDelay(reconnectDelay()); connection->setSecure(isSecure()); connection->setSaslMechanism(saslMechanism()); return connection; } /*! This property holds the FALLBACK encoding for received messages. The fallback encoding is used when the message is detected not to be valid \c UTF-8 and the consequent auto-detection of message encoding fails. See QTextCodec::availableCodecs() for the list of supported encodings. The default value is \c ISO-8859-15. \par Access functions: \li QByteArray <b>encoding</b>() const \li void <b>setEncoding</b>(const QByteArray& encoding) \sa QTextCodec::availableCodecs(), QTextCodec::codecForLocale() */ QByteArray IrcConnection::encoding() const { Q_D(const IrcConnection); return d->encoding; } void IrcConnection::setEncoding(const QByteArray& encoding) { Q_D(IrcConnection); extern bool irc_is_supported_encoding(const QByteArray& encoding); // ircmessagedecoder.cpp if (!irc_is_supported_encoding(encoding)) { qWarning() << "IrcConnection::setEncoding(): unsupported encoding" << encoding; return; } d->encoding = encoding; } /*! This property holds the server host. \par Access functions: \li QString <b>host</b>() const \li void <b>setHost</b>(const QString& host) \par Notifier signal: \li void <b>hostChanged</b>(const QString& host) */ QString IrcConnection::host() const { Q_D(const IrcConnection); return d->host; } void IrcConnection::setHost(const QString& host) { Q_D(IrcConnection); if (d->host != host) { if (isActive()) qWarning("IrcConnection::setHost() has no effect until re-connect"); const QString oldName = displayName(); d->host = host; emit hostChanged(host); const QString newName = displayName(); if (oldName != newName) emit displayNameChanged(newName); } } /*! This property holds the server port. The default value is \c 6667. \par Access functions: \li int <b>port</b>() const \li void <b>setPort</b>(int port) \par Notifier signal: \li void <b>portChanged</b>(int port) */ int IrcConnection::port() const { Q_D(const IrcConnection); return d->port; } void IrcConnection::setPort(int port) { Q_D(IrcConnection); if (d->port != port) { if (isActive()) qWarning("IrcConnection::setPort() has no effect until re-connect"); d->port = port; emit portChanged(port); } } /*! \since 3.3 This property holds the list of servers. The list of servers is automatically cycled through when reconnecting. \par Access functions: \li QStringList <b>servers</b>() const \li void <b>setServers</b>(const QStringList& servers) \par Notifier signal: \li void <b>serversChanged</b>(const QStringList& servers) \sa isValidServer() */ QStringList IrcConnection::servers() const { Q_D(const IrcConnection); return d->servers; } void IrcConnection::setServers(const QStringList& servers) { Q_D(IrcConnection); if (d->servers != servers) { d->servers = servers; emit serversChanged(servers); } } /*! \since 3.3 Returns \c true if the server line syntax is valid. The syntax is: \code host <[+]port> \endcode where port is optional (defaults to \c 6667) and \c + prefix denotes SSL. \sa servers */ bool IrcConnection::isValidServer(const QString& server) { QString h; int p; bool s; return parseServer(server, &h, &p, &s); } /*! This property holds the user name. \note Changing the user name has no effect until the connection is re-established. \par Access functions: \li QString <b>userName</b>() const \li void <b>setUserName</b>(const QString& name) \par Notifier signal: \li void <b>userNameChanged</b>(const QString& name) */ QString IrcConnection::userName() const { Q_D(const IrcConnection); return d->userName; } void IrcConnection::setUserName(const QString& name) { Q_D(IrcConnection); QString user = name.split(" ", QString::SkipEmptyParts).value(0).trimmed(); if (d->userName != user) { if (isActive()) qWarning("IrcConnection::setUserName() has no effect until re-connect"); d->userName = user; emit userNameChanged(user); } } /*! This property holds the current nick name. \par Access functions: \li QString <b>nickName</b>() const \li void <b>setNickName</b>(const QString& name) \par Notifier signal: \li void <b>nickNameChanged</b>(const QString& name) \sa nickNames */ QString IrcConnection::nickName() const { Q_D(const IrcConnection); return d->nickName; } void IrcConnection::setNickName(const QString& name) { Q_D(IrcConnection); QString nick = name.split(" ", QString::SkipEmptyParts).value(0).trimmed(); if (d->nickName != nick) { if (isActive()) sendCommand(IrcCommand::createNick(nick)); else d->setNick(nick); } } /*! This property holds the real name. \note Changing the real name has no effect until the connection is re-established. \par Access functions: \li QString <b>realName</b>() const \li void <b>setRealName</b>(const QString& name) \par Notifier signal: \li void <b>realNameChanged</b>(const QString& name) */ QString IrcConnection::realName() const { Q_D(const IrcConnection); return d->realName; } void IrcConnection::setRealName(const QString& name) { Q_D(IrcConnection); if (d->realName != name) { if (isActive()) qWarning("IrcConnection::setRealName() has no effect until re-connect"); d->realName = name; emit realNameChanged(name); } } /*! This property holds the password. \par Access functions: \li QString <b>password</b>() const \li void <b>setPassword</b>(const QString& password) \par Notifier signal: \li void <b>passwordChanged</b>(const QString& password) */ QString IrcConnection::password() const { Q_D(const IrcConnection); return d->password; } void IrcConnection::setPassword(const QString& password) { Q_D(IrcConnection); if (d->password != password) { if (isActive()) qWarning("IrcConnection::setPassword() has no effect until re-connect"); d->password = password; emit passwordChanged(password); } } /*! \since 3.3 This property holds the nick names. The list of nick names is automatically cycled through when the current nick name is reserved. If all provided nick names are reserved, the nickNameRequired() signal is emitted. \par Access functions: \li QStringList <b>nickNames</b>() const \li void <b>setNickNames</b>(const QStringList& names) \par Notifier signal: \li void <b>nickNamesChanged</b>(const QStringList& names) \sa nickName, nickNameRequired() */ QStringList IrcConnection::nickNames() const { Q_D(const IrcConnection); return d->nickNames; } void IrcConnection::setNickNames(const QStringList& names) { Q_D(IrcConnection); if (d->nickNames != names) { d->nickNames = names; emit nickNamesChanged(names); } } /*! This property holds the display name. Unless explicitly set, display name resolves to IrcNetwork::name or IrcConnection::host while the former is not known. \par Access functions: \li QString <b>displayName</b>() const \li void <b>setDisplayName</b>(const QString& name) \par Notifier signal: \li void <b>displayNameChanged</b>(const QString& name) */ QString IrcConnection::displayName() const { Q_D(const IrcConnection); QString name = d->displayName; if (name.isEmpty()) name = d->network->name(); if (name.isEmpty()) name = d->host; return name; } void IrcConnection::setDisplayName(const QString& name) { Q_D(IrcConnection); if (d->displayName != name) { d->displayName = name; emit displayNameChanged(name); } } /*! \since 3.1 This property holds arbitrary user data. \par Access functions: \li QVariantMap <b>userData</b>() const \li void <b>setUserData</b>(const QVariantMap& data) \par Notifier signal: \li void <b>userDataChanged</b>(const QVariantMap& data) */ QVariantMap IrcConnection::userData() const { Q_D(const IrcConnection); return d->userData; } void IrcConnection::setUserData(const QVariantMap& data) { Q_D(IrcConnection); if (d->userData != data) { d->userData = data; emit userDataChanged(data); } } /*! \property Status IrcConnection::status This property holds the connection status. \par Access function: \li Status <b>status</b>() const \par Notifier signal: \li void <b>statusChanged</b>(Status status) */ IrcConnection::Status IrcConnection::status() const { Q_D(const IrcConnection); return d->status; } /*! \property bool IrcConnection::active This property holds whether the connection is active. The connection is considered active when its either connecting, connected or closing. \par Access function: \li bool <b>isActive</b>() const */ bool IrcConnection::isActive() const { Q_D(const IrcConnection); return d->status == Connecting || d->status == Connected || d->status == Closing; } /*! \property bool IrcConnection::connected This property holds whether the connection has been established. The connection has been established when the welcome message has been received and the server is ready to receive commands. \sa Irc::RPL_WELCOME \par Access function: \li bool <b>isConnected</b>() const \par Notifier signal: \li void <b>connected</b>() */ bool IrcConnection::isConnected() const { Q_D(const IrcConnection); return d->status == Connected; } /*! \property bool IrcConnection::enabled This property holds whether the connection is enabled. The default value is \c true. When set to \c false, a disabled connection does nothing when open() is called. \par Access functions: \li bool <b>isEnabled</b>() const \li void <b>setEnabled</b>(bool enabled) [slot] \li void <b>setDisabled</b>(bool disabled) [slot] \par Notifier signal: \li void <b>enabledChanged</b>(bool enabled) */ bool IrcConnection::isEnabled() const { Q_D(const IrcConnection); return d->enabled; } void IrcConnection::setEnabled(bool enabled) { Q_D(IrcConnection); if (d->enabled != enabled) { d->enabled = enabled; emit enabledChanged(enabled); } } void IrcConnection::setDisabled(bool disabled) { setEnabled(!disabled); } /*! \property int IrcConnection::reconnectDelay This property holds the reconnect delay in seconds. A positive (greater than zero) value enables automatic reconnect. When the connection is lost due to a socket error, IrcConnection will automatically attempt to reconnect after the specified delay. The default value is \c 0 (automatic reconnect disabled). \par Access functions: \li int <b>reconnectDelay</b>() const \li void <b>setReconnectDelay</b>(int seconds) \par Notifier signal: \li void <b>reconnectDelayChanged</b>(int seconds) */ int IrcConnection::reconnectDelay() const { Q_D(const IrcConnection); return d->reconnecter.interval() / 1000; } void IrcConnection::setReconnectDelay(int seconds) { Q_D(IrcConnection); const int interval = qMax(0, seconds) * 1000; if (d->reconnecter.interval() != interval) { d->reconnecter.setInterval(interval); emit reconnectDelayChanged(interval); } } /*! This property holds the socket. The default value is an instance of QTcpSocket. The previously set socket is deleted if its parent is \c this. \note IrcConnection supports QSslSocket in the way that it automatically calls QSslSocket::startClientEncryption() while connecting. \par Access functions: \li \ref QAbstractSocket* <b>socket</b>() const \li void <b>setSocket</b>(\ref QAbstractSocket* socket) \sa IrcConnection::secure */ QAbstractSocket* IrcConnection::socket() const { Q_D(const IrcConnection); return d->socket; } void IrcConnection::setSocket(QAbstractSocket* socket) { Q_D(IrcConnection); if (d->socket != socket) { if (d->socket) { d->socket->disconnect(this); if (d->socket->parent() == this) d->socket->deleteLater(); } d->socket = socket; if (socket) { connect(socket, SIGNAL(connected()), this, SLOT(_irc_connected())); connect(socket, SIGNAL(disconnected()), this, SLOT(_irc_disconnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(_irc_readData())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(_irc_error(QAbstractSocket::SocketError))); connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(_irc_state(QAbstractSocket::SocketState))); if (isSecure()) connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(_irc_sslErrors())); } } } /*! \property bool IrcConnection::secure This property holds whether the socket is an SSL socket. This property is provided for convenience. Calling \code connection->setSecure(true); \endcode is equivalent to: \code QSslSocket* socket = new QSslSocket(socket); socket->setPeerVerifyMode(QSslSocket::QueryPeer); connection->setSocket(socket); \endcode \note IrcConnection does not handle SSL errors, see QSslSocket::sslErrors() for more details on the subject. \par Access functions: \li bool <b>isSecure</b>() const \li void <b>setSecure</b>(bool secure) \par Notifier signal: \li void <b>secureChanged</b>(bool secure) \sa secureSupported, IrcConnection::socket */ bool IrcConnection::isSecure() const { #ifdef QT_NO_SSL return false; #else return qobject_cast<QSslSocket*>(socket()); #endif // QT_NO_SSL } void IrcConnection::setSecure(bool secure) { #ifdef QT_NO_SSL if (secure) { qWarning("IrcConnection::setSecure(): the Qt build does not support SSL"); return; } #else if (secure && !QSslSocket::supportsSsl()) { qWarning("IrcConnection::setSecure(): the platform does not support SSL - try installing OpenSSL"); return; } QSslSocket* sslSocket = qobject_cast<QSslSocket*>(socket()); if (secure && !sslSocket) { sslSocket = new QSslSocket(this); sslSocket->setPeerVerifyMode(QSslSocket::QueryPeer); setSocket(sslSocket); emit secureChanged(true); } else if (!secure && sslSocket) { setSocket(new QTcpSocket(this)); emit secureChanged(false); } #endif // !QT_NO_SSL } /*! \deprecated Use Irc::isSecureSupported() instead. */ bool IrcConnection::isSecureSupported() { return Irc::isSecureSupported(); } /*! This property holds the used SASL (Simple Authentication and Security Layer) mechanism. \par Access functions: \li QString <b>saslMechanism</b>() const \li void <b>setSaslMechanism</b>(const QString& mechanism) \par Notifier signal: \li void <b>saslMechanismChanged</b>(const QString& mechanism) \sa supportedSaslMechanisms, \ref ircv3 */ QString IrcConnection::saslMechanism() const { Q_D(const IrcConnection); return d->saslMechanism; } void IrcConnection::setSaslMechanism(const QString& mechanism) { Q_D(IrcConnection); if (!mechanism.isEmpty() && !supportedSaslMechanisms().contains(mechanism.toUpper())) { qWarning("IrcConnection::setSaslMechanism(): unsupported mechanism: '%s'", qPrintable(mechanism)); return; } if (d->saslMechanism != mechanism) { if (isActive()) qWarning("IrcConnection::setSaslMechanism() has no effect until re-connect"); d->saslMechanism = mechanism.toUpper(); emit saslMechanismChanged(mechanism); } } /*! \deprecated Use Irc::supportedSaslMechanisms() instead. */ QStringList IrcConnection::supportedSaslMechanisms() { return Irc::supportedSaslMechanisms(); } /*! \since 3.5 This property holds CTCP (client to client protocol) replies. This is a convenient request-reply map for customized static CTCP replies. For dynamic replies, override createCtcpReply() instead. \note Set an empty reply to omit the automatic reply. \par Access functions: \li QVariantMap <b>ctcpReplies</b>() const \li void <b>setCtcpReplies</b>(const QVariantMap& replies) \par Notifier signal: \li void <b>ctcpRepliesChanged</b>(const QVariantMap& replies) \sa createCtcpReply() */ QVariantMap IrcConnection::ctcpReplies() const { Q_D(const IrcConnection); return d->ctcpReplies; } void IrcConnection::setCtcpReplies(const QVariantMap& replies) { Q_D(IrcConnection); if (d->ctcpReplies != replies) { d->ctcpReplies = replies; emit ctcpRepliesChanged(replies); } } /*! This property holds the network information. \par Access function: \li IrcNetwork* <b>network</b>() const */ IrcNetwork* IrcConnection::network() const { Q_D(const IrcConnection); return d->network; } /*! Opens a connection to the server. The function does nothing when the connection is already \ref active or explicitly \ref enabled "disabled". \note The function merely outputs a warnings and returns immediately if either \ref host, \ref userName, \ref nickName or \ref realName is empty. */ void IrcConnection::open() { Q_D(IrcConnection); if (d->host.isEmpty() && d->servers.isEmpty()) { qWarning("IrcConnection::open(): host is empty!"); return; } if (d->userName.isEmpty()) { qWarning("IrcConnection::open(): userName is empty!"); return; } if (d->nickName.isEmpty() && d->nickNames.isEmpty()) { qWarning("IrcConnection::open(): nickNames is empty!"); return; } if (d->realName.isEmpty()) { qWarning("IrcConnection::open(): realName is empty!"); return; } if (d->enabled && d->socket) d->open(); } /*! Immediately closes the connection to the server. Calling close() makes the connection close immediately and thus might lead to "remote host closed the connection". In order to quit gracefully, call quit() first. This function attempts to flush the underlying socket, but this does not guarantee that the server ever receives the QUIT command if the connection is closed immediately after sending the command. In order to ensure a graceful quit, let the server handle closing the connection. C++ example: \code connection->quit(reason); QTimer::singleShot(timeout, connection, SLOT(deleteLater())); \endcode QML example: \code connection.quit(reason); connection.destroy(timeout); \endcode \sa quit() */ void IrcConnection::close() { Q_D(IrcConnection); if (d->socket) { d->closed = true; d->pendingOpen = false; d->socket->flush(); d->socket->abort(); d->socket->disconnectFromHost(); if (d->socket->state() == QAbstractSocket::UnconnectedState) d->setStatus(Closed); d->reconnecter.stop(); } } /*! Sends a quit command with an optionally specified \a reason. This method is provided for convenience. It is equal to: \code if (connection->isActive()) connection->sendCommand(IrcCommand::createQuit(reason)); \endcode \sa IrcCommand::createQuit() */ void IrcConnection::quit(const QString& reason) { if (isConnected()) sendCommand(IrcCommand::createQuit(reason)); else close(); } /*! Sends a \a command to the server. If the connection is not active, the \a command is queued and sent later when the connection has been established. \note If the command has a valid parent, it is an indication that the caller of this method is be responsible for freeing the command. If the command does not have a valid parent (like the commands created via various IrcCommand::createXxx() methods) the connection will take ownership of the command and delete it once it has been sent. Thus, the command must have been allocated on the heap and it is not safe to access the command after it has been sent. \sa sendData() */ bool IrcConnection::sendCommand(IrcCommand* command) { Q_D(IrcConnection); bool res = false; if (command) { bool filtered = false; IrcCommandPrivate::get(command)->connection = this; for (int i = d->commandFilters.count() - 1; !filtered && i >= 0; --i) { QObject* filter = d->commandFilters.at(i); IrcCommandFilter* commandFilter = qobject_cast<IrcCommandFilter*>(filter); if (commandFilter && !d->activeCommandFilters.contains(filter)) { d->activeCommandFilters.push(filter); filtered |= commandFilter->commandFilter(command); d->activeCommandFilters.pop(); } } if (filtered) { res = false; } else { QTextCodec* codec = QTextCodec::codecForName(command->encoding()); Q_ASSERT(codec); res = sendData(codec->fromUnicode(command->toString())); } if (!command->parent()) command->deleteLater(); } return res; } /*! Sends raw \a data to the server. \sa sendCommand() */ bool IrcConnection::sendData(const QByteArray& data) { Q_D(IrcConnection); if (d->socket) { if (isActive()) { const QByteArray cmd = data.left(5).toUpper(); if (cmd.startsWith("PASS ")) ircDebug(this, IrcDebug::Write) << data.left(5) + QByteArray(data.mid(5).length(), 'x'); else ircDebug(this, IrcDebug::Write) << data; if (!d->closed && data.length() >= 4) { if (cmd.startsWith("QUIT") && (data.length() == 4 || QChar(data.at(4)).isSpace())) d->closed = true; } return d->protocol->write(data); } else { d->pendingData += data; } } return false; } /*! Sends raw \a message to the server using UTF-8 encoding. \sa sendData(), sendCommand() */ bool IrcConnection::sendRaw(const QString& message) { return sendData(message.toUtf8()); } /*! Installs a message \a filter on the connection. The \a filter must implement the IrcMessageFilter interface. A message filter receives all messages that are sent to the connection. The filter receives messages via the \ref IrcMessageFilter::messageFilter() "messageFilter()" function. The function must return \c true if the message should be filtered, (i.e. stopped); otherwise it must return \c false. If multiple message filters are installed on the same connection, the filter that was installed last is activated first. \sa removeMessageFilter() */ void IrcConnection::installMessageFilter(QObject* filter) { Q_D(IrcConnection); IrcMessageFilter* msgFilter = qobject_cast<IrcMessageFilter*>(filter); if (msgFilter) { d->messageFilters += filter; connect(filter, SIGNAL(destroyed(QObject*)), this, SLOT(_irc_filterDestroyed(QObject*)), Qt::UniqueConnection); } } /*! Removes a message \a filter from the connection. The request is ignored if such message filter has not been installed. All message filters for a connection are automatically removed when the connection is destroyed. \sa installMessageFilter() */ void IrcConnection::removeMessageFilter(QObject* filter) { Q_D(IrcConnection); IrcMessageFilter* msgFilter = qobject_cast<IrcMessageFilter*>(filter); if (msgFilter) { d->messageFilters.removeAll(filter); disconnect(filter, SIGNAL(destroyed(QObject*)), this, SLOT(_irc_filterDestroyed(QObject*))); } } /*! Installs a command \a filter on the connection. The \a filter must implement the IrcCommandFilter interface. A command filter receives all commands that are sent from the connection. The filter receives commands via the \ref IrcCommandFilter::commandFilter() "commandFilter()" function. The function must return \c true if the command should be filtered, (i.e. stopped); otherwise it must return \c false. If multiple command filters are installed on the same connection, the filter that was installed last is activated first. \sa removeCommandFilter() */ void IrcConnection::installCommandFilter(QObject* filter) { Q_D(IrcConnection); IrcCommandFilter* cmdFilter = qobject_cast<IrcCommandFilter*>(filter); if (cmdFilter) { d->commandFilters += filter; connect(filter, SIGNAL(destroyed(QObject*)), this, SLOT(_irc_filterDestroyed(QObject*)), Qt::UniqueConnection); } } /*! Removes a command \a filter from the connection. The request is ignored if such command filter has not been installed. All command filters for a connection are automatically removed when the connection is destroyed. \sa installCommandFilter() */ void IrcConnection::removeCommandFilter(QObject* filter) { Q_D(IrcConnection); IrcCommandFilter* cmdFilter = qobject_cast<IrcCommandFilter*>(filter); if (cmdFilter) { d->commandFilters.removeAll(filter); disconnect(filter, SIGNAL(destroyed(QObject*)), this, SLOT(_irc_filterDestroyed(QObject*))); } } /*! \since 3.1 Saves the state of the connection. The \a version number is stored as part of the state data. To restore the saved state, pass the return value and \a version number to restoreState(). */ QByteArray IrcConnection::saveState(int version) const { Q_D(const IrcConnection); QVariantMap args; args.insert("version", version); args.insert("host", d->host); args.insert("port", d->port); args.insert("servers", d->servers); args.insert("userName", d->userName); args.insert("nickName", d->nickName); args.insert("realName", d->realName); args.insert("password", d->password); args.insert("nickNames", d->nickNames); args.insert("displayName", displayName()); args.insert("userData", d->userData); args.insert("encoding", d->encoding); args.insert("enabled", d->enabled); args.insert("reconnectDelay", reconnectDelay()); args.insert("secure", isSecure()); args.insert("saslMechanism", d->saslMechanism); QByteArray state; QDataStream out(&state, QIODevice::WriteOnly); out << args; return state; } /*! \since 3.1 Restores the \a state of the connection. The \a version number is compared with that stored in \a state. If they do not match, the connection state is left unchanged, and this function returns \c false; otherwise, the state is restored, and \c true is returned. \sa saveState() */ bool IrcConnection::restoreState(const QByteArray& state, int version) { Q_D(IrcConnection); if (isActive()) return false; QVariantMap args; QDataStream in(state); in >> args; if (in.status() != QDataStream::Ok || args.value("version", -1).toInt() != version) return false; setHost(args.value("host", d->host).toString()); setPort(args.value("port", d->port).toInt()); setServers(args.value("servers", d->servers).toStringList()); setUserName(args.value("userName", d->userName).toString()); setNickName(args.value("nickName", d->nickName).toString()); setRealName(args.value("realName", d->realName).toString()); setPassword(args.value("password", d->password).toString()); setNickNames(args.value("nickNames", d->nickNames).toStringList()); if (!d->nickNames.isEmpty() && d->nickNames.indexOf(d->nickName) != 0) setNickName(d->nickNames.first()); setDisplayName(args.value("displayName").toString()); setUserData(args.value("userData", d->userData).toMap()); setEncoding(args.value("encoding", d->encoding).toByteArray()); setEnabled(args.value("enabled", d->enabled).toBool()); setReconnectDelay(args.value("reconnectDelay", reconnectDelay()).toInt()); setSecure(args.value("secure", isSecure()).toBool()); setSaslMechanism(args.value("saslMechanism", d->saslMechanism).toString()); return true; } /*! Creates a reply command for the CTCP \a request. The default implementation first checks whether the \ref ctcpReplies property contains a user-supplied reply for the request. In case it does, the reply is sent automatically. In case there is no user-supplied reply, the default implementation handles the following CTCP requests: CLIENTINFO, PING, SOURCE, TIME and VERSION. Reimplement this function in order to alter or omit the default replies. \sa ctcpReplies */ IrcCommand* IrcConnection::createCtcpReply(IrcPrivateMessage* request) const { Q_D(const IrcConnection); QString reply; QString type = request->content().split(" ", QString::SkipEmptyParts).value(0).toUpper(); if (d->ctcpReplies.contains(type)) reply = type + QLatin1String(" ") + d->ctcpReplies.value(type).toString(); else if (type == "PING") reply = request->content(); else if (type == "TIME") reply = QLatin1String("TIME ") + QLocale().toString(QDateTime::currentDateTime(), QLocale::ShortFormat); else if (type == "VERSION") reply = QLatin1String("VERSION Communi ") + Irc::version() + QLatin1String(" - https://communi.github.io"); else if (type == "SOURCE") reply = QLatin1String("SOURCE https://communi.github.io"); else if (type == "CLIENTINFO") reply = QLatin1String("CLIENTINFO PING SOURCE TIME VERSION"); if (!reply.isEmpty()) return IrcCommand::createCtcpReply(request->nick(), reply); return 0; } /*! \since 3.2 This property holds the protocol. The previously set protocol is deleted if its parent is \c this. \par Access functions: \li \ref IrcProtocol* <b>protocol</b>() const \li void <b>setProtocol</b>(\ref IrcProtocol* protocol) */ IrcProtocol* IrcConnection::protocol() const { Q_D(const IrcConnection); return d->protocol; } void IrcConnection::setProtocol(IrcProtocol* proto) { Q_D(IrcConnection); if (d->protocol != proto) { if (d->protocol && d->protocol->parent() == this) delete d->protocol; d->protocol = proto; } } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug debug, IrcConnection::Status status) { const int index = IrcConnection::staticMetaObject.indexOfEnumerator("Status"); QMetaEnum enumerator = IrcConnection::staticMetaObject.enumerator(index); const char* key = enumerator.valueToKey(status); debug << (key ? key : "Unknown"); return debug; } QDebug operator<<(QDebug debug, const IrcConnection* connection) { if (!connection) return debug << "IrcConnection(0x0) "; debug.nospace() << connection->metaObject()->className() << '(' << (void*) connection; if (!connection->displayName().isEmpty()) debug.nospace() << ", " << qPrintable(connection->displayName()); debug.nospace() << ')'; return debug.space(); } #endif // QT_NO_DEBUG_STREAM #include "moc_ircconnection.cpp" IRC_END_NAMESPACE
bsd-3-clause
timopulkkinen/BubbleFish
content/browser/ssl/ssl_request_info.h
1555
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_SSL_SSL_REQUEST_INFO_H_ #define CONTENT_BROWSER_SSL_SSL_REQUEST_INFO_H_ #include <string> #include "base/memory/ref_counted.h" #include "googleurl/src/gurl.h" #include "net/base/cert_status_flags.h" #include "webkit/glue/resource_type.h" namespace content { // SSLRequestInfo wraps up the information SSLPolicy needs about a request in // order to update our security IU. SSLRequestInfo is RefCounted in case we // need to deal with the request asynchronously. class SSLRequestInfo : public base::RefCounted<SSLRequestInfo> { public: SSLRequestInfo(const GURL& url, ResourceType::Type resource_type, int child_id, int ssl_cert_id, net::CertStatus ssl_cert_status); const GURL& url() const { return url_; } ResourceType::Type resource_type() const { return resource_type_; } int child_id() const { return child_id_; } int ssl_cert_id() const { return ssl_cert_id_; } net::CertStatus ssl_cert_status() const { return ssl_cert_status_; } private: friend class base::RefCounted<SSLRequestInfo>; virtual ~SSLRequestInfo(); GURL url_; ResourceType::Type resource_type_; int child_id_; int ssl_cert_id_; net::CertStatus ssl_cert_status_; DISALLOW_COPY_AND_ASSIGN(SSLRequestInfo); }; } // namespace content #endif // CONTENT_BROWSER_SSL_SSL_REQUEST_INFO_H_
bsd-3-clause
dededong/goblin-core
riscv/llvm/3.5/binutils-2.21.1/bfd/elf32-frv.c
219982
/* FRV-specific support for 32-bit ELF. Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. This file is part of BFD, the Binary File Descriptor library. 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 3 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., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sysdep.h" #include "bfd.h" #include "libbfd.h" #include "elf-bfd.h" #include "elf/frv.h" #include "dwarf2.h" #include "hashtab.h" /* Forward declarations. */ static bfd_reloc_status_type elf32_frv_relocate_lo16 PARAMS ((bfd *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_hi16 PARAMS ((bfd *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_label24 PARAMS ((bfd *, asection *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_gprel12 PARAMS ((struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_gprelu12 PARAMS ((struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_gprello PARAMS ((struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static bfd_reloc_status_type elf32_frv_relocate_gprelhi PARAMS ((struct bfd_link_info *, bfd *, asection *, Elf_Internal_Rela *, bfd_byte *, bfd_vma)); static reloc_howto_type *frv_reloc_type_lookup PARAMS ((bfd *, bfd_reloc_code_real_type)); static void frv_info_to_howto_rela PARAMS ((bfd *, arelent *, Elf_Internal_Rela *)); static bfd_boolean elf32_frv_relocate_section PARAMS ((bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, Elf_Internal_Sym *, asection **)); static bfd_boolean elf32_frv_add_symbol_hook PARAMS (( bfd *, struct bfd_link_info *, Elf_Internal_Sym *, const char **, flagword *, asection **, bfd_vma *)); static bfd_reloc_status_type frv_final_link_relocate PARAMS ((reloc_howto_type *, bfd *, asection *, bfd_byte *, Elf_Internal_Rela *, bfd_vma)); static bfd_boolean elf32_frv_check_relocs PARAMS ((bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *)); static int elf32_frv_machine PARAMS ((bfd *)); static bfd_boolean elf32_frv_object_p PARAMS ((bfd *)); static bfd_boolean frv_elf_set_private_flags PARAMS ((bfd *, flagword)); static bfd_boolean frv_elf_copy_private_bfd_data PARAMS ((bfd *, bfd *)); static bfd_boolean frv_elf_merge_private_bfd_data PARAMS ((bfd *, bfd *)); static bfd_boolean frv_elf_print_private_bfd_data PARAMS ((bfd *, PTR)); static bfd_boolean elf32_frv_grok_prstatus (bfd * abfd, Elf_Internal_Note * note); static bfd_boolean elf32_frv_grok_psinfo (bfd * abfd, Elf_Internal_Note * note); static reloc_howto_type elf32_frv_howto_table [] = { /* This reloc does nothing. */ HOWTO (R_FRV_NONE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_NONE", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 32 bit absolute relocation. */ HOWTO (R_FRV_32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_32", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 16 bit pc-relative relocation. */ HOWTO (R_FRV_LABEL16, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_LABEL16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ TRUE), /* pcrel_offset */ /* A 24-bit pc-relative relocation. */ HOWTO (R_FRV_LABEL24, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 26, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_LABEL24", /* name */ FALSE, /* partial_inplace */ 0x7e03ffff, /* src_mask */ 0x7e03ffff, /* dst_mask */ TRUE), /* pcrel_offset */ HOWTO (R_FRV_LO16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_LO16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_HI16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_HI16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_GPREL12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GPREL12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_GPRELU12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GPRELU12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0x3f03f, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_GPREL32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GPREL32", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_GPRELHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GPRELHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_FRV_GPRELLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GPRELLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOT12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOT12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOTHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOTLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The 32-bit address of the canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the address of canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOT12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOT12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the address of the canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOTHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOTHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the address of the canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOTLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOTLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The 64-bit descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_VALUE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 64, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_VALUE", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the address of canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOTOFF12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOTOFF12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the address of the canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOTOFFHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOTOFFHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the address of the canonical descriptor of a function. */ HOWTO (R_FRV_FUNCDESC_GOTOFFLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_GOTOFFLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOTOFF12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTOFF12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOTOFFHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTOFFHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the address of the symbol. */ HOWTO (R_FRV_GOTOFFLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTOFFLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 24-bit pc-relative relocation referencing the TLS PLT entry for a thread-local symbol. If the symbol number is 0, it refers to the module. */ HOWTO (R_FRV_GETTLSOFF, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 26, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GETTLSOFF", /* name */ FALSE, /* partial_inplace */ 0x7e03ffff, /* src_mask */ 0x7e03ffff, /* dst_mask */ TRUE), /* pcrel_offset */ /* A 64-bit TLS descriptor for a symbol. This relocation is only valid as a REL, dynamic relocation. */ HOWTO (R_FRV_TLSDESC_VALUE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 64, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSDESC_VALUE", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the TLS descriptor of the symbol. */ HOWTO (R_FRV_GOTTLSDESC12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSDESC12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the TLS descriptor of the symbol. */ HOWTO (R_FRV_GOTTLSDESCHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSDESCHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the TLS descriptor of the symbol. */ HOWTO (R_FRV_GOTTLSDESCLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSDESCLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the offset from the module base address to the thread-local symbol address. */ HOWTO (R_FRV_TLSMOFF12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSMOFF12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the offset from the module base address to the thread-local symbol address. */ HOWTO (R_FRV_TLSMOFFHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSMOFFHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the offset from the module base address to the thread-local symbol address. */ HOWTO (R_FRV_TLSMOFFLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSMOFFLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 12-bit signed operand with the GOT offset for the TLSOFF entry for a symbol. */ HOWTO (R_FRV_GOTTLSOFF12, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 12, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSOFF12", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The upper 16 bits of the GOT offset for the TLSOFF entry for a symbol. */ HOWTO (R_FRV_GOTTLSOFFHI, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSOFFHI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The lower 16 bits of the GOT offset for the TLSOFF entry for a symbol. */ HOWTO (R_FRV_GOTTLSOFFLO, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GOTTLSOFFLO", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* The 32-bit offset from the thread pointer (not the module base address) to a thread-local symbol. */ HOWTO (R_FRV_TLSOFF, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSOFF", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* An annotation for linker relaxation, that denotes the symbol+addend whose TLS descriptor is referenced by the sum of the two input registers of an ldd instruction. */ HOWTO (R_FRV_TLSDESC_RELAX, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSDESC_RELAX", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* An annotation for linker relaxation, that denotes the symbol+addend whose TLS resolver entry point is given by the sum of the two register operands of an calll instruction. */ HOWTO (R_FRV_GETTLSOFF_RELAX, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_GETTLSOFF_RELAX", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* An annotation for linker relaxation, that denotes the symbol+addend whose TLS offset GOT entry is given by the sum of the two input registers of an ld instruction. */ HOWTO (R_FRV_TLSOFF_RELAX, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSOFF_RELAX", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 32-bit offset from the module base address to the thread-local symbol address. */ HOWTO (R_FRV_TLSMOFF, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSMOFF", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ }; /* GNU extension to record C++ vtable hierarchy. */ static reloc_howto_type elf32_frv_vtinherit_howto = HOWTO (R_FRV_GNU_VTINHERIT, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ NULL, /* special_function */ "R_FRV_GNU_VTINHERIT", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE); /* pcrel_offset */ /* GNU extension to record C++ vtable member usage. */ static reloc_howto_type elf32_frv_vtentry_howto = HOWTO (R_FRV_GNU_VTENTRY, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ _bfd_elf_rel_vtable_reloc_fn, /* special_function */ "R_FRV_GNU_VTENTRY", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE); /* pcrel_offset */ /* The following 3 relocations are REL. The only difference to the entries in the table above are that partial_inplace is TRUE. */ static reloc_howto_type elf32_frv_rel_32_howto = HOWTO (R_FRV_32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_32", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE); /* pcrel_offset */ static reloc_howto_type elf32_frv_rel_funcdesc_howto = HOWTO (R_FRV_FUNCDESC, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE); /* pcrel_offset */ static reloc_howto_type elf32_frv_rel_funcdesc_value_howto = HOWTO (R_FRV_FUNCDESC_VALUE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 64, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_FUNCDESC_VALUE", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE); /* pcrel_offset */ static reloc_howto_type elf32_frv_rel_tlsdesc_value_howto = /* A 64-bit TLS descriptor for a symbol. The first word resolves to an entry point, and the second resolves to a special argument. If the symbol turns out to be in static TLS, the entry point is a return instruction, and the special argument is the TLS offset for the symbol. If it's in dynamic TLS, the entry point is a TLS offset resolver, and the special argument is a pointer to a data structure allocated by the dynamic loader, containing the GOT address for the offset resolver, the module id, the offset within the module, and anything else the TLS offset resolver might need to determine the TLS offset for the symbol in the running thread. */ HOWTO (R_FRV_TLSDESC_VALUE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 64, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSDESC_VALUE", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE); /* pcrel_offset */ static reloc_howto_type elf32_frv_rel_tlsoff_howto = /* The 32-bit offset from the thread pointer (not the module base address) to a thread-local symbol. */ HOWTO (R_FRV_TLSOFF, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_FRV_TLSOFF", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE); /* pcrel_offset */ extern const bfd_target bfd_elf32_frvfdpic_vec; #define IS_FDPIC(bfd) ((bfd)->xvec == &bfd_elf32_frvfdpic_vec) /* An extension of the elf hash table data structure, containing some additional FRV-specific data. */ struct frvfdpic_elf_link_hash_table { struct elf_link_hash_table elf; /* A pointer to the .got section. */ asection *sgot; /* A pointer to the .rel.got section. */ asection *sgotrel; /* A pointer to the .rofixup section. */ asection *sgotfixup; /* A pointer to the .plt section. */ asection *splt; /* A pointer to the .rel.plt section. */ asection *spltrel; /* GOT base offset. */ bfd_vma got0; /* Location of the first non-lazy PLT entry, i.e., the number of bytes taken by lazy PLT entries. If locally-bound TLS descriptors require a ret instruction, it will be placed at this offset. */ bfd_vma plt0; /* A hash table holding information about which symbols were referenced with which PIC-related relocations. */ struct htab *relocs_info; /* Summary reloc information collected by _frvfdpic_count_got_plt_entries. */ struct _frvfdpic_dynamic_got_info *g; }; /* Get the FRV ELF linker hash table from a link_info structure. */ #define frvfdpic_hash_table(p) \ (elf_hash_table_id ((struct elf_link_hash_table *) ((p)->hash)) \ == FRV_ELF_DATA ? ((struct frvfdpic_elf_link_hash_table *) ((p)->hash)) : NULL) #define frvfdpic_got_section(info) \ (frvfdpic_hash_table (info)->sgot) #define frvfdpic_gotrel_section(info) \ (frvfdpic_hash_table (info)->sgotrel) #define frvfdpic_gotfixup_section(info) \ (frvfdpic_hash_table (info)->sgotfixup) #define frvfdpic_plt_section(info) \ (frvfdpic_hash_table (info)->splt) #define frvfdpic_pltrel_section(info) \ (frvfdpic_hash_table (info)->spltrel) #define frvfdpic_relocs_info(info) \ (frvfdpic_hash_table (info)->relocs_info) #define frvfdpic_got_initial_offset(info) \ (frvfdpic_hash_table (info)->got0) #define frvfdpic_plt_initial_offset(info) \ (frvfdpic_hash_table (info)->plt0) #define frvfdpic_dynamic_got_plt_info(info) \ (frvfdpic_hash_table (info)->g) /* Currently it's the same, but if some day we have a reason to change it, we'd better be using a different macro. FIXME: if there's any TLS PLT entry that uses local-exec or initial-exec models, we could use the ret at the end of any of them instead of adding one more. */ #define frvfdpic_plt_tls_ret_offset(info) \ (frvfdpic_plt_initial_offset (info)) /* The name of the dynamic interpreter. This is put in the .interp section. */ #define ELF_DYNAMIC_INTERPRETER "/lib/ld.so.1" #define DEFAULT_STACK_SIZE 0x20000 /* This structure is used to collect the number of entries present in each addressable range of the got. */ struct _frvfdpic_dynamic_got_info { /* Several bits of information about the current link. */ struct bfd_link_info *info; /* Total GOT size needed for GOT entries within the 12-, 16- or 32-bit ranges. */ bfd_vma got12, gotlos, gothilo; /* Total GOT size needed for function descriptor entries within the 12-, 16- or 32-bit ranges. */ bfd_vma fd12, fdlos, fdhilo; /* Total GOT size needed by function descriptor entries referenced in PLT entries, that would be profitable to place in offsets close to the PIC register. */ bfd_vma fdplt; /* Total PLT size needed by lazy PLT entries. */ bfd_vma lzplt; /* Total GOT size needed for TLS descriptor entries within the 12-, 16- or 32-bit ranges. */ bfd_vma tlsd12, tlsdlos, tlsdhilo; /* Total GOT size needed by TLS descriptors referenced in PLT entries, that would be profitable to place in offers close to the PIC register. */ bfd_vma tlsdplt; /* Total PLT size needed by TLS lazy PLT entries. */ bfd_vma tlslzplt; /* Number of relocations carried over from input object files. */ unsigned long relocs; /* Number of fixups introduced by relocations in input object files. */ unsigned long fixups; /* The number of fixups that reference the ret instruction added to the PLT for locally-resolved TLS descriptors. */ unsigned long tls_ret_refs; }; /* This structure is used to assign offsets to got entries, function descriptors, plt entries and lazy plt entries. */ struct _frvfdpic_dynamic_got_plt_info { /* Summary information collected with _frvfdpic_count_got_plt_entries. */ struct _frvfdpic_dynamic_got_info g; /* For each addressable range, we record a MAX (positive) and MIN (negative) value. CUR is used to assign got entries, and it's incremented from an initial positive value to MAX, then from MIN to FDCUR (unless FDCUR wraps around first). FDCUR is used to assign function descriptors, and it's decreased from an initial non-positive value to MIN, then from MAX down to CUR (unless CUR wraps around first). All of MIN, MAX, CUR and FDCUR always point to even words. ODD, if non-zero, indicates an odd word to be used for the next got entry, otherwise CUR is used and incremented by a pair of words, wrapping around when it reaches MAX. FDCUR is decremented (and wrapped) before the next function descriptor is chosen. FDPLT indicates the number of remaining slots that can be used for function descriptors used only by PLT entries. TMAX, TMIN and TCUR are used to assign TLS descriptors. TCUR starts as MAX, and grows up to TMAX, then wraps around to TMIN and grows up to MIN. TLSDPLT indicates the number of remaining slots that can be used for TLS descriptors used only by TLS PLT entries. */ struct _frvfdpic_dynamic_got_alloc_data { bfd_signed_vma max, cur, odd, fdcur, min; bfd_signed_vma tmax, tcur, tmin; bfd_vma fdplt, tlsdplt; } got12, gotlos, gothilo; }; /* Create an FRV ELF linker hash table. */ static struct bfd_link_hash_table * frvfdpic_elf_link_hash_table_create (bfd *abfd) { struct frvfdpic_elf_link_hash_table *ret; bfd_size_type amt = sizeof (struct frvfdpic_elf_link_hash_table); ret = bfd_zalloc (abfd, amt); if (ret == NULL) return NULL; if (!_bfd_elf_link_hash_table_init (&ret->elf, abfd, _bfd_elf_link_hash_newfunc, sizeof (struct elf_link_hash_entry), FRV_ELF_DATA)) { free (ret); return NULL; } return &ret->elf.root; } /* Decide whether a reference to a symbol can be resolved locally or not. If the symbol is protected, we want the local address, but its function descriptor must be assigned by the dynamic linker. */ #define FRVFDPIC_SYM_LOCAL(INFO, H) \ (_bfd_elf_symbol_refs_local_p ((H), (INFO), 1) \ || ! elf_hash_table (INFO)->dynamic_sections_created) #define FRVFDPIC_FUNCDESC_LOCAL(INFO, H) \ ((H)->dynindx == -1 || ! elf_hash_table (INFO)->dynamic_sections_created) /* This structure collects information on what kind of GOT, PLT or function descriptors are required by relocations that reference a certain symbol. */ struct frvfdpic_relocs_info { /* The index of the symbol, as stored in the relocation r_info, if we have a local symbol; -1 otherwise. */ long symndx; union { /* The input bfd in which the symbol is defined, if it's a local symbol. */ bfd *abfd; /* If symndx == -1, the hash table entry corresponding to a global symbol (even if it turns out to bind locally, in which case it should ideally be replaced with section's symndx + addend). */ struct elf_link_hash_entry *h; } d; /* The addend of the relocation that references the symbol. */ bfd_vma addend; /* The fields above are used to identify an entry. The fields below contain information on how an entry is used and, later on, which locations it was assigned. */ /* The following 3 fields record whether the symbol+addend above was ever referenced with a GOT relocation. The 12 suffix indicates a GOT12 relocation; los is used for GOTLO relocations that are not matched by a GOTHI relocation; hilo is used for GOTLO/GOTHI pairs. */ unsigned got12:1; unsigned gotlos:1; unsigned gothilo:1; /* Whether a FUNCDESC relocation references symbol+addend. */ unsigned fd:1; /* Whether a FUNCDESC_GOT relocation references symbol+addend. */ unsigned fdgot12:1; unsigned fdgotlos:1; unsigned fdgothilo:1; /* Whether a FUNCDESC_GOTOFF relocation references symbol+addend. */ unsigned fdgoff12:1; unsigned fdgofflos:1; unsigned fdgoffhilo:1; /* Whether a GETTLSOFF relocation references symbol+addend. */ unsigned tlsplt:1; /* FIXME: we should probably add tlspltdesc, tlspltoff and tlspltimm, to tell what kind of TLS PLT entry we're generating. We might instead just pre-compute flags telling whether the object is suitable for local exec, initial exec or general dynamic addressing, and use that all over the place. We could also try to do a better job of merging TLSOFF and TLSDESC entries in main executables, but perhaps we can get rid of TLSDESC entirely in them instead. */ /* Whether a GOTTLSDESC relocation references symbol+addend. */ unsigned tlsdesc12:1; unsigned tlsdesclos:1; unsigned tlsdeschilo:1; /* Whether a GOTTLSOFF relocation references symbol+addend. */ unsigned tlsoff12:1; unsigned tlsofflos:1; unsigned tlsoffhilo:1; /* Whether symbol+addend is referenced with GOTOFF12, GOTOFFLO or GOTOFFHI relocations. The addend doesn't really matter, since we envision that this will only be used to check whether the symbol is mapped to the same segment as the got. */ unsigned gotoff:1; /* Whether symbol+addend is referenced by a LABEL24 relocation. */ unsigned call:1; /* Whether symbol+addend is referenced by a 32 or FUNCDESC_VALUE relocation. */ unsigned sym:1; /* Whether we need a PLT entry for a symbol. Should be implied by something like: (call && symndx == -1 && ! FRVFDPIC_SYM_LOCAL (info, d.h)) */ unsigned plt:1; /* Whether a function descriptor should be created in this link unit for symbol+addend. Should be implied by something like: (plt || fdgotoff12 || fdgotofflos || fdgotofflohi || ((fd || fdgot12 || fdgotlos || fdgothilo) && (symndx != -1 || FRVFDPIC_FUNCDESC_LOCAL (info, d.h)))) */ unsigned privfd:1; /* Whether a lazy PLT entry is needed for this symbol+addend. Should be implied by something like: (privfd && symndx == -1 && ! FRVFDPIC_SYM_LOCAL (info, d.h) && ! (info->flags & DF_BIND_NOW)) */ unsigned lazyplt:1; /* Whether we've already emitted GOT relocations and PLT entries as needed for this symbol. */ unsigned done:1; /* The number of R_FRV_32, R_FRV_FUNCDESC, R_FRV_FUNCDESC_VALUE and R_FRV_TLSDESC_VALUE, R_FRV_TLSOFF relocations referencing symbol+addend. */ unsigned relocs32, relocsfd, relocsfdv, relocstlsd, relocstlsoff; /* The number of .rofixups entries and dynamic relocations allocated for this symbol, minus any that might have already been used. */ unsigned fixups, dynrelocs; /* The offsets of the GOT entries assigned to symbol+addend, to the function descriptor's address, and to a function descriptor, respectively. Should be zero if unassigned. The offsets are counted from the value that will be assigned to the PIC register, not from the beginning of the .got section. */ bfd_signed_vma got_entry, fdgot_entry, fd_entry; /* The offsets of the PLT entries assigned to symbol+addend, non-lazy and lazy, respectively. If unassigned, should be (bfd_vma)-1. */ bfd_vma plt_entry, lzplt_entry; /* The offsets of the GOT entries for TLS offset and TLS descriptor. */ bfd_signed_vma tlsoff_entry, tlsdesc_entry; /* The offset of the TLS offset PLT entry. */ bfd_vma tlsplt_entry; }; /* Compute a hash with the key fields of an frvfdpic_relocs_info entry. */ static hashval_t frvfdpic_relocs_info_hash (const void *entry_) { const struct frvfdpic_relocs_info *entry = entry_; return (entry->symndx == -1 ? (long) entry->d.h->root.root.hash : entry->symndx + (long) entry->d.abfd->id * 257) + entry->addend; } /* Test whether the key fields of two frvfdpic_relocs_info entries are identical. */ static int frvfdpic_relocs_info_eq (const void *entry1, const void *entry2) { const struct frvfdpic_relocs_info *e1 = entry1; const struct frvfdpic_relocs_info *e2 = entry2; return e1->symndx == e2->symndx && e1->addend == e2->addend && (e1->symndx == -1 ? e1->d.h == e2->d.h : e1->d.abfd == e2->d.abfd); } /* Find or create an entry in a hash table HT that matches the key fields of the given ENTRY. If it's not found, memory for a new entry is allocated in ABFD's obstack. */ static struct frvfdpic_relocs_info * frvfdpic_relocs_info_find (struct htab *ht, bfd *abfd, const struct frvfdpic_relocs_info *entry, enum insert_option insert) { struct frvfdpic_relocs_info **loc = (struct frvfdpic_relocs_info **) htab_find_slot (ht, entry, insert); if (! loc) return NULL; if (*loc) return *loc; *loc = bfd_zalloc (abfd, sizeof (**loc)); if (! *loc) return *loc; (*loc)->symndx = entry->symndx; (*loc)->d = entry->d; (*loc)->addend = entry->addend; (*loc)->plt_entry = (bfd_vma)-1; (*loc)->lzplt_entry = (bfd_vma)-1; (*loc)->tlsplt_entry = (bfd_vma)-1; return *loc; } /* Obtain the address of the entry in HT associated with H's symbol + addend, creating a new entry if none existed. ABFD is only used for memory allocation purposes. */ inline static struct frvfdpic_relocs_info * frvfdpic_relocs_info_for_global (struct htab *ht, bfd *abfd, struct elf_link_hash_entry *h, bfd_vma addend, enum insert_option insert) { struct frvfdpic_relocs_info entry; entry.symndx = -1; entry.d.h = h; entry.addend = addend; return frvfdpic_relocs_info_find (ht, abfd, &entry, insert); } /* Obtain the address of the entry in HT associated with the SYMNDXth local symbol of the input bfd ABFD, plus the addend, creating a new entry if none existed. */ inline static struct frvfdpic_relocs_info * frvfdpic_relocs_info_for_local (struct htab *ht, bfd *abfd, long symndx, bfd_vma addend, enum insert_option insert) { struct frvfdpic_relocs_info entry; entry.symndx = symndx; entry.d.abfd = abfd; entry.addend = addend; return frvfdpic_relocs_info_find (ht, abfd, &entry, insert); } /* Merge fields set by check_relocs() of two entries that end up being mapped to the same (presumably global) symbol. */ inline static void frvfdpic_pic_merge_early_relocs_info (struct frvfdpic_relocs_info *e2, struct frvfdpic_relocs_info const *e1) { e2->got12 |= e1->got12; e2->gotlos |= e1->gotlos; e2->gothilo |= e1->gothilo; e2->fd |= e1->fd; e2->fdgot12 |= e1->fdgot12; e2->fdgotlos |= e1->fdgotlos; e2->fdgothilo |= e1->fdgothilo; e2->fdgoff12 |= e1->fdgoff12; e2->fdgofflos |= e1->fdgofflos; e2->fdgoffhilo |= e1->fdgoffhilo; e2->tlsplt |= e1->tlsplt; e2->tlsdesc12 |= e1->tlsdesc12; e2->tlsdesclos |= e1->tlsdesclos; e2->tlsdeschilo |= e1->tlsdeschilo; e2->tlsoff12 |= e1->tlsoff12; e2->tlsofflos |= e1->tlsofflos; e2->tlsoffhilo |= e1->tlsoffhilo; e2->gotoff |= e1->gotoff; e2->call |= e1->call; e2->sym |= e1->sym; } /* Every block of 65535 lazy PLT entries shares a single call to the resolver, inserted in the 32768th lazy PLT entry (i.e., entry # 32767, counting from 0). All other lazy PLT entries branch to it in a single instruction. */ #define FRVFDPIC_LZPLT_BLOCK_SIZE ((bfd_vma) 8 * 65535 + 4) #define FRVFDPIC_LZPLT_RESOLV_LOC (8 * 32767) /* Add a dynamic relocation to the SRELOC section. */ inline static bfd_vma _frvfdpic_add_dyn_reloc (bfd *output_bfd, asection *sreloc, bfd_vma offset, int reloc_type, long dynindx, bfd_vma addend, struct frvfdpic_relocs_info *entry) { Elf_Internal_Rela outrel; bfd_vma reloc_offset; outrel.r_offset = offset; outrel.r_info = ELF32_R_INFO (dynindx, reloc_type); outrel.r_addend = addend; reloc_offset = sreloc->reloc_count * sizeof (Elf32_External_Rel); BFD_ASSERT (reloc_offset < sreloc->size); bfd_elf32_swap_reloc_out (output_bfd, &outrel, sreloc->contents + reloc_offset); sreloc->reloc_count++; /* If the entry's index is zero, this relocation was probably to a linkonce section that got discarded. We reserved a dynamic relocation, but it was for another entry than the one we got at the time of emitting the relocation. Unfortunately there's no simple way for us to catch this situation, since the relocation is cleared right before calling relocate_section, at which point we no longer know what the relocation used to point to. */ if (entry->symndx) { BFD_ASSERT (entry->dynrelocs > 0); entry->dynrelocs--; } return reloc_offset; } /* Add a fixup to the ROFIXUP section. */ static bfd_vma _frvfdpic_add_rofixup (bfd *output_bfd, asection *rofixup, bfd_vma offset, struct frvfdpic_relocs_info *entry) { bfd_vma fixup_offset; if (rofixup->flags & SEC_EXCLUDE) return -1; fixup_offset = rofixup->reloc_count * 4; if (rofixup->contents) { BFD_ASSERT (fixup_offset < rofixup->size); bfd_put_32 (output_bfd, offset, rofixup->contents + fixup_offset); } rofixup->reloc_count++; if (entry && entry->symndx) { /* See discussion about symndx == 0 in _frvfdpic_add_dyn_reloc above. */ BFD_ASSERT (entry->fixups > 0); entry->fixups--; } return fixup_offset; } /* Find the segment number in which OSEC, and output section, is located. */ static unsigned _frvfdpic_osec_to_segment (bfd *output_bfd, asection *osec) { Elf_Internal_Phdr *p = _bfd_elf_find_segment_containing_section (output_bfd, osec); return (p != NULL) ? p - elf_tdata (output_bfd)->phdr : -1; } inline static bfd_boolean _frvfdpic_osec_readonly_p (bfd *output_bfd, asection *osec) { unsigned seg = _frvfdpic_osec_to_segment (output_bfd, osec); return ! (elf_tdata (output_bfd)->phdr[seg].p_flags & PF_W); } #define FRVFDPIC_TLS_BIAS (2048 - 16) /* Return the base VMA address which should be subtracted from real addresses when resolving TLSMOFF relocation. This is PT_TLS segment p_vaddr, plus the 2048-16 bias. */ static bfd_vma tls_biased_base (struct bfd_link_info *info) { /* If tls_sec is NULL, we should have signalled an error already. */ if (elf_hash_table (info)->tls_sec == NULL) return FRVFDPIC_TLS_BIAS; return elf_hash_table (info)->tls_sec->vma + FRVFDPIC_TLS_BIAS; } /* Generate relocations for GOT entries, function descriptors, and code for PLT and lazy PLT entries. */ inline static bfd_boolean _frvfdpic_emit_got_relocs_plt_entries (struct frvfdpic_relocs_info *entry, bfd *output_bfd, struct bfd_link_info *info, asection *sec, Elf_Internal_Sym *sym, bfd_vma addend) { bfd_vma fd_lazy_rel_offset = (bfd_vma)-1; int dynindx = -1; if (entry->done) return TRUE; entry->done = 1; if (entry->got_entry || entry->fdgot_entry || entry->fd_entry || entry->tlsoff_entry || entry->tlsdesc_entry) { /* If the symbol is dynamic, consider it for dynamic relocations, otherwise decay to section + offset. */ if (entry->symndx == -1 && entry->d.h->dynindx != -1) dynindx = entry->d.h->dynindx; else { if (sec && sec->output_section && ! bfd_is_abs_section (sec->output_section) && ! bfd_is_und_section (sec->output_section)) dynindx = elf_section_data (sec->output_section)->dynindx; else dynindx = 0; } } /* Generate relocation for GOT entry pointing to the symbol. */ if (entry->got_entry) { int idx = dynindx; bfd_vma ad = addend; /* If the symbol is dynamic but binds locally, use section+offset. */ if (sec && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (entry->symndx == -1) ad += entry->d.h->root.u.def.value; else ad += sym->st_value; ad += sec->output_offset; if (sec->output_section && elf_section_data (sec->output_section)) idx = elf_section_data (sec->output_section)->dynindx; else idx = 0; } /* If we're linking an executable at a fixed address, we can omit the dynamic relocation as long as the symbol is local to this module. */ if (info->executable && !info->pie && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (sec) ad += sec->output_section->vma; if (entry->symndx != -1 || entry->d.h->root.type != bfd_link_hash_undefweak) _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), frvfdpic_got_section (info)->output_section ->vma + frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info) + entry->got_entry, entry); } else _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), _bfd_elf_section_offset (output_bfd, info, frvfdpic_got_section (info), frvfdpic_got_initial_offset (info) + entry->got_entry) + frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info)->output_offset, R_FRV_32, idx, ad, entry); bfd_put_32 (output_bfd, ad, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->got_entry); } /* Generate relocation for GOT entry pointing to a canonical function descriptor. */ if (entry->fdgot_entry) { int reloc, idx; bfd_vma ad = 0; if (! (entry->symndx == -1 && entry->d.h->root.type == bfd_link_hash_undefweak && FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { /* If the symbol is dynamic and there may be dynamic symbol resolution because we are, or are linked with, a shared library, emit a FUNCDESC relocation such that the dynamic linker will allocate the function descriptor. If the symbol needs a non-local function descriptor but binds locally (e.g., its visibility is protected, emit a dynamic relocation decayed to section+offset. */ if (entry->symndx == -1 && ! FRVFDPIC_FUNCDESC_LOCAL (info, entry->d.h) && FRVFDPIC_SYM_LOCAL (info, entry->d.h) && !(info->executable && !info->pie)) { reloc = R_FRV_FUNCDESC; idx = elf_section_data (entry->d.h->root.u.def.section ->output_section)->dynindx; ad = entry->d.h->root.u.def.section->output_offset + entry->d.h->root.u.def.value; } else if (entry->symndx == -1 && ! FRVFDPIC_FUNCDESC_LOCAL (info, entry->d.h)) { reloc = R_FRV_FUNCDESC; idx = dynindx; ad = addend; if (ad) { (*info->callbacks->reloc_dangerous) (info, _("relocation requires zero addend"), elf_hash_table (info)->dynobj, frvfdpic_got_section (info), entry->fdgot_entry); return FALSE; } } else { /* Otherwise, we know we have a private function descriptor, so reference it directly. */ if (elf_hash_table (info)->dynamic_sections_created) BFD_ASSERT (entry->privfd); reloc = R_FRV_32; idx = elf_section_data (frvfdpic_got_section (info) ->output_section)->dynindx; ad = frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info) + entry->fd_entry; } /* If there is room for dynamic symbol resolution, emit the dynamic relocation. However, if we're linking an executable at a fixed location, we won't have emitted a dynamic symbol entry for the got section, so idx will be zero, which means we can and should compute the address of the private descriptor ourselves. */ if (info->executable && !info->pie && (entry->symndx != -1 || FRVFDPIC_FUNCDESC_LOCAL (info, entry->d.h))) { ad += frvfdpic_got_section (info)->output_section->vma; _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset + frvfdpic_got_initial_offset (info) + entry->fdgot_entry, entry); } else _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), _bfd_elf_section_offset (output_bfd, info, frvfdpic_got_section (info), frvfdpic_got_initial_offset (info) + entry->fdgot_entry) + frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset, reloc, idx, ad, entry); } bfd_put_32 (output_bfd, ad, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->fdgot_entry); } /* Generate relocation to fill in a private function descriptor in the GOT. */ if (entry->fd_entry) { int idx = dynindx; bfd_vma ad = addend; bfd_vma ofst; long lowword, highword; /* If the symbol is dynamic but binds locally, use section+offset. */ if (sec && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (entry->symndx == -1) ad += entry->d.h->root.u.def.value; else ad += sym->st_value; ad += sec->output_offset; if (sec->output_section && elf_section_data (sec->output_section)) idx = elf_section_data (sec->output_section)->dynindx; else idx = 0; } /* If we're linking an executable at a fixed address, we can omit the dynamic relocation as long as the symbol is local to this module. */ if (info->executable && !info->pie && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (sec) ad += sec->output_section->vma; ofst = 0; if (entry->symndx != -1 || entry->d.h->root.type != bfd_link_hash_undefweak) { _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset + frvfdpic_got_initial_offset (info) + entry->fd_entry, entry); _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset + frvfdpic_got_initial_offset (info) + entry->fd_entry + 4, entry); } } else { ofst = _frvfdpic_add_dyn_reloc (output_bfd, entry->lazyplt ? frvfdpic_pltrel_section (info) : frvfdpic_gotrel_section (info), _bfd_elf_section_offset (output_bfd, info, frvfdpic_got_section (info), frvfdpic_got_initial_offset (info) + entry->fd_entry) + frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset, R_FRV_FUNCDESC_VALUE, idx, ad, entry); } /* If we've omitted the dynamic relocation, just emit the fixed addresses of the symbol and of the local GOT base offset. */ if (info->executable && !info->pie && sec && sec->output_section) { lowword = ad; highword = frvfdpic_got_section (info)->output_section->vma + frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info); } else if (entry->lazyplt) { if (ad) { (*info->callbacks->reloc_dangerous) (info, _("relocation requires zero addend"), elf_hash_table (info)->dynobj, frvfdpic_got_section (info), entry->fd_entry); return FALSE; } fd_lazy_rel_offset = ofst; /* A function descriptor used for lazy or local resolving is initialized such that its high word contains the output section index in which the PLT entries are located, and the low word contains the address of the lazy PLT entry entry point, that must be within the memory region assigned to that section. */ lowword = entry->lzplt_entry + 4 + frvfdpic_plt_section (info)->output_offset + frvfdpic_plt_section (info)->output_section->vma; highword = _frvfdpic_osec_to_segment (output_bfd, frvfdpic_plt_section (info)->output_section); } else { /* A function descriptor for a local function gets the index of the section. For a non-local function, it's disregarded. */ lowword = ad; if (sec == NULL || (entry->symndx == -1 && entry->d.h->dynindx != -1 && entry->d.h->dynindx == idx)) highword = 0; else highword = _frvfdpic_osec_to_segment (output_bfd, sec->output_section); } bfd_put_32 (output_bfd, lowword, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->fd_entry); bfd_put_32 (output_bfd, highword, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->fd_entry + 4); } /* Generate code for the PLT entry. */ if (entry->plt_entry != (bfd_vma) -1) { bfd_byte *plt_code = frvfdpic_plt_section (info)->contents + entry->plt_entry; BFD_ASSERT (entry->fd_entry); /* Figure out what kind of PLT entry we need, depending on the location of the function descriptor within the GOT. */ if (entry->fd_entry >= -(1 << (12 - 1)) && entry->fd_entry < (1 << (12 - 1))) { /* lddi @(gr15, fd_entry), gr14 */ bfd_put_32 (output_bfd, 0x9cccf000 | (entry->fd_entry & ((1 << 12) - 1)), plt_code); plt_code += 4; } else { if (entry->fd_entry >= -(1 << (16 - 1)) && entry->fd_entry < (1 << (16 - 1))) { /* setlos lo(fd_entry), gr14 */ bfd_put_32 (output_bfd, 0x9cfc0000 | (entry->fd_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } else { /* sethi.p hi(fd_entry), gr14 setlo lo(fd_entry), gr14 */ bfd_put_32 (output_bfd, 0x1cf80000 | ((entry->fd_entry >> 16) & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; bfd_put_32 (output_bfd, 0x9cf40000 | (entry->fd_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } /* ldd @(gr14,gr15),gr14 */ bfd_put_32 (output_bfd, 0x9c08e14f, plt_code); plt_code += 4; } /* jmpl @(gr14,gr0) */ bfd_put_32 (output_bfd, 0x8030e000, plt_code); } /* Generate code for the lazy PLT entry. */ if (entry->lzplt_entry != (bfd_vma) -1) { bfd_byte *lzplt_code = frvfdpic_plt_section (info)->contents + entry->lzplt_entry; bfd_vma resolverStub_addr; bfd_put_32 (output_bfd, fd_lazy_rel_offset, lzplt_code); lzplt_code += 4; resolverStub_addr = entry->lzplt_entry / FRVFDPIC_LZPLT_BLOCK_SIZE * FRVFDPIC_LZPLT_BLOCK_SIZE + FRVFDPIC_LZPLT_RESOLV_LOC; if (resolverStub_addr >= frvfdpic_plt_initial_offset (info)) resolverStub_addr = frvfdpic_plt_initial_offset (info) - 12; if (entry->lzplt_entry == resolverStub_addr) { /* This is a lazy PLT entry that includes a resolver call. */ /* ldd @(gr15,gr0), gr4 jmpl @(gr4,gr0) */ bfd_put_32 (output_bfd, 0x8808f140, lzplt_code); bfd_put_32 (output_bfd, 0x80304000, lzplt_code + 4); } else { /* bra resolverStub */ bfd_put_32 (output_bfd, 0xc01a0000 | (((resolverStub_addr - entry->lzplt_entry) / 4) & (((bfd_vma)1 << 16) - 1)), lzplt_code); } } /* Generate relocation for GOT entry holding the TLS offset. */ if (entry->tlsoff_entry) { int idx = dynindx; bfd_vma ad = addend; if (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h)) { /* If the symbol is dynamic but binds locally, use section+offset. */ if (sec) { if (entry->symndx == -1) ad += entry->d.h->root.u.def.value; else ad += sym->st_value; ad += sec->output_offset; if (sec->output_section && elf_section_data (sec->output_section)) idx = elf_section_data (sec->output_section)->dynindx; else idx = 0; } } /* *ABS*+addend is special for TLS relocations, use only the addend. */ if (info->executable && idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) ; /* If we're linking an executable, we can entirely omit the dynamic relocation if the symbol is local to this module. */ else if (info->executable && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (sec) ad += sec->output_section->vma - tls_biased_base (info); } else { if (idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) { if (! elf_hash_table (info)->tls_sec) { (*info->callbacks->undefined_symbol) (info, "TLS section", elf_hash_table (info)->dynobj, frvfdpic_got_section (info), entry->tlsoff_entry, TRUE); return FALSE; } idx = elf_section_data (elf_hash_table (info)->tls_sec)->dynindx; ad += FRVFDPIC_TLS_BIAS; } _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), _bfd_elf_section_offset (output_bfd, info, frvfdpic_got_section (info), frvfdpic_got_initial_offset (info) + entry->tlsoff_entry) + frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset, R_FRV_TLSOFF, idx, ad, entry); } bfd_put_32 (output_bfd, ad, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->tlsoff_entry); } if (entry->tlsdesc_entry) { int idx = dynindx; bfd_vma ad = addend; /* If the symbol is dynamic but binds locally, use section+offset. */ if (sec && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { if (entry->symndx == -1) ad += entry->d.h->root.u.def.value; else ad += sym->st_value; ad += sec->output_offset; if (sec->output_section && elf_section_data (sec->output_section)) idx = elf_section_data (sec->output_section)->dynindx; else idx = 0; } /* If we didn't set up a TLS offset entry, but we're linking an executable and the symbol binds locally, we can use the module offset in the TLS descriptor in relaxations. */ if (info->executable && ! entry->tlsoff_entry) entry->tlsoff_entry = entry->tlsdesc_entry + 4; if (info->executable && !info->pie && ((idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) || entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { /* *ABS*+addend is special for TLS relocations, use only the addend for the TLS offset, and take the module id as 0. */ if (idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) ; /* For other TLS symbols that bind locally, add the section TLS offset to the addend. */ else if (sec) ad += sec->output_section->vma - tls_biased_base (info); bfd_put_32 (output_bfd, frvfdpic_plt_section (info)->output_section->vma + frvfdpic_plt_section (info)->output_offset + frvfdpic_plt_tls_ret_offset (info), frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->tlsdesc_entry); _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset + frvfdpic_got_initial_offset (info) + entry->tlsdesc_entry, entry); BFD_ASSERT (frvfdpic_dynamic_got_plt_info (info)->tls_ret_refs); /* We've used one of the reserved fixups, so discount it so that we can check at the end that we've used them all. */ frvfdpic_dynamic_got_plt_info (info)->tls_ret_refs--; /* While at that, make sure the ret instruction makes to the right location in the PLT. We could do it only when we got to 0, but since the check at the end will only print a warning, make sure we have the ret in place in case the warning is missed. */ bfd_put_32 (output_bfd, 0xc03a4000, frvfdpic_plt_section (info)->contents + frvfdpic_plt_tls_ret_offset (info)); } else { if (idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) { if (! elf_hash_table (info)->tls_sec) { (*info->callbacks->undefined_symbol) (info, "TLS section", elf_hash_table (info)->dynobj, frvfdpic_got_section (info), entry->tlsdesc_entry, TRUE); return FALSE; } idx = elf_section_data (elf_hash_table (info)->tls_sec)->dynindx; ad += FRVFDPIC_TLS_BIAS; } _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), _bfd_elf_section_offset (output_bfd, info, frvfdpic_got_section (info), frvfdpic_got_initial_offset (info) + entry->tlsdesc_entry) + frvfdpic_got_section (info) ->output_section->vma + frvfdpic_got_section (info) ->output_offset, R_FRV_TLSDESC_VALUE, idx, ad, entry); bfd_put_32 (output_bfd, 0, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->tlsdesc_entry); } bfd_put_32 (output_bfd, ad, frvfdpic_got_section (info)->contents + frvfdpic_got_initial_offset (info) + entry->tlsdesc_entry + 4); } /* Generate code for the get-TLS-offset PLT entry. */ if (entry->tlsplt_entry != (bfd_vma) -1) { bfd_byte *plt_code = frvfdpic_plt_section (info)->contents + entry->tlsplt_entry; if (info->executable && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (info, entry->d.h))) { int idx = dynindx; bfd_vma ad = addend; /* sec may be NULL when referencing an undefweak symbol while linking a static executable. */ if (!sec) { BFD_ASSERT (entry->symndx == -1 && entry->d.h->root.type == bfd_link_hash_undefweak); } else { if (entry->symndx == -1) ad += entry->d.h->root.u.def.value; else ad += sym->st_value; ad += sec->output_offset; if (sec->output_section && elf_section_data (sec->output_section)) idx = elf_section_data (sec->output_section)->dynindx; else idx = 0; } /* *ABS*+addend is special for TLS relocations, use only the addend for the TLS offset, and take the module id as 0. */ if (idx == 0 && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) ; /* For other TLS symbols that bind locally, add the section TLS offset to the addend. */ else if (sec) ad += sec->output_section->vma - tls_biased_base (info); if ((bfd_signed_vma)ad >= -(1 << (16 - 1)) && (bfd_signed_vma)ad < (1 << (16 - 1))) { /* setlos lo(ad), gr9 */ bfd_put_32 (output_bfd, 0x92fc0000 | (ad & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } else { /* sethi.p hi(ad), gr9 setlo lo(ad), gr9 */ bfd_put_32 (output_bfd, 0x12f80000 | ((ad >> 16) & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; bfd_put_32 (output_bfd, 0x92f40000 | (ad & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } /* ret */ bfd_put_32 (output_bfd, 0xc03a4000, plt_code); } else if (entry->tlsoff_entry) { /* Figure out what kind of PLT entry we need, depending on the location of the TLS descriptor within the GOT. */ if (entry->tlsoff_entry >= -(1 << (12 - 1)) && entry->tlsoff_entry < (1 << (12 - 1))) { /* ldi @(gr15, tlsoff_entry), gr9 */ bfd_put_32 (output_bfd, 0x92c8f000 | (entry->tlsoff_entry & ((1 << 12) - 1)), plt_code); plt_code += 4; } else { if (entry->tlsoff_entry >= -(1 << (16 - 1)) && entry->tlsoff_entry < (1 << (16 - 1))) { /* setlos lo(tlsoff_entry), gr8 */ bfd_put_32 (output_bfd, 0x90fc0000 | (entry->tlsoff_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } else { /* sethi.p hi(tlsoff_entry), gr8 setlo lo(tlsoff_entry), gr8 */ bfd_put_32 (output_bfd, 0x10f80000 | ((entry->tlsoff_entry >> 16) & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; bfd_put_32 (output_bfd, 0x90f40000 | (entry->tlsoff_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } /* ld @(gr15,gr8),gr9 */ bfd_put_32 (output_bfd, 0x9008f108, plt_code); plt_code += 4; } /* ret */ bfd_put_32 (output_bfd, 0xc03a4000, plt_code); } else { BFD_ASSERT (entry->tlsdesc_entry); /* Figure out what kind of PLT entry we need, depending on the location of the TLS descriptor within the GOT. */ if (entry->tlsdesc_entry >= -(1 << (12 - 1)) && entry->tlsdesc_entry < (1 << (12 - 1))) { /* lddi @(gr15, tlsdesc_entry), gr8 */ bfd_put_32 (output_bfd, 0x90ccf000 | (entry->tlsdesc_entry & ((1 << 12) - 1)), plt_code); plt_code += 4; } else { if (entry->tlsdesc_entry >= -(1 << (16 - 1)) && entry->tlsdesc_entry < (1 << (16 - 1))) { /* setlos lo(tlsdesc_entry), gr8 */ bfd_put_32 (output_bfd, 0x90fc0000 | (entry->tlsdesc_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } else { /* sethi.p hi(tlsdesc_entry), gr8 setlo lo(tlsdesc_entry), gr8 */ bfd_put_32 (output_bfd, 0x10f80000 | ((entry->tlsdesc_entry >> 16) & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; bfd_put_32 (output_bfd, 0x90f40000 | (entry->tlsdesc_entry & (((bfd_vma)1 << 16) - 1)), plt_code); plt_code += 4; } /* ldd @(gr15,gr8),gr8 */ bfd_put_32 (output_bfd, 0x9008f148, plt_code); plt_code += 4; } /* jmpl @(gr8,gr0) */ bfd_put_32 (output_bfd, 0x80308000, plt_code); } } return TRUE; } /* Handle an FRV small data reloc. */ static bfd_reloc_status_type elf32_frv_relocate_gprel12 (info, input_bfd, input_section, relocation, contents, value) struct bfd_link_info *info; bfd *input_bfd; asection *input_section; Elf_Internal_Rela *relocation; bfd_byte *contents; bfd_vma value; { bfd_vma insn; bfd_vma gp; struct bfd_link_hash_entry *h; h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE); gp = (h->u.def.value + h->u.def.section->output_section->vma + h->u.def.section->output_offset); value -= input_section->output_section->vma; value -= (gp - input_section->output_section->vma); insn = bfd_get_32 (input_bfd, contents + relocation->r_offset); value += relocation->r_addend; if ((long) value > 0x7ff || (long) value < -0x800) return bfd_reloc_overflow; bfd_put_32 (input_bfd, (insn & 0xfffff000) | (value & 0xfff), contents + relocation->r_offset); return bfd_reloc_ok; } /* Handle an FRV small data reloc. for the u12 field. */ static bfd_reloc_status_type elf32_frv_relocate_gprelu12 (info, input_bfd, input_section, relocation, contents, value) struct bfd_link_info *info; bfd *input_bfd; asection *input_section; Elf_Internal_Rela *relocation; bfd_byte *contents; bfd_vma value; { bfd_vma insn; bfd_vma gp; struct bfd_link_hash_entry *h; bfd_vma mask; h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE); gp = (h->u.def.value + h->u.def.section->output_section->vma + h->u.def.section->output_offset); value -= input_section->output_section->vma; value -= (gp - input_section->output_section->vma); insn = bfd_get_32 (input_bfd, contents + relocation->r_offset); value += relocation->r_addend; if ((long) value > 0x7ff || (long) value < -0x800) return bfd_reloc_overflow; /* The high 6 bits go into bits 17-12. The low 6 bits go into bits 5-0. */ mask = 0x3f03f; insn = (insn & ~mask) | ((value & 0xfc0) << 12) | (value & 0x3f); bfd_put_32 (input_bfd, insn, contents + relocation->r_offset); return bfd_reloc_ok; } /* Handle an FRV ELF HI16 reloc. */ static bfd_reloc_status_type elf32_frv_relocate_hi16 (input_bfd, relhi, contents, value) bfd *input_bfd; Elf_Internal_Rela *relhi; bfd_byte *contents; bfd_vma value; { bfd_vma insn; insn = bfd_get_32 (input_bfd, contents + relhi->r_offset); value += relhi->r_addend; value = ((value >> 16) & 0xffff); insn = (insn & 0xffff0000) | value; if ((long) value > 0xffff || (long) value < -0x10000) return bfd_reloc_overflow; bfd_put_32 (input_bfd, insn, contents + relhi->r_offset); return bfd_reloc_ok; } static bfd_reloc_status_type elf32_frv_relocate_lo16 (input_bfd, rello, contents, value) bfd *input_bfd; Elf_Internal_Rela *rello; bfd_byte *contents; bfd_vma value; { bfd_vma insn; insn = bfd_get_32 (input_bfd, contents + rello->r_offset); value += rello->r_addend; value = value & 0xffff; insn = (insn & 0xffff0000) | value; if ((long) value > 0xffff || (long) value < -0x10000) return bfd_reloc_overflow; bfd_put_32 (input_bfd, insn, contents + rello->r_offset); return bfd_reloc_ok; } /* Perform the relocation for the CALL label24 instruction. */ static bfd_reloc_status_type elf32_frv_relocate_label24 (input_bfd, input_section, rello, contents, value) bfd *input_bfd; asection *input_section; Elf_Internal_Rela *rello; bfd_byte *contents; bfd_vma value; { bfd_vma insn; bfd_vma label6; bfd_vma label18; /* The format for the call instruction is: 0 000000 0001111 000000000000000000 label6 opcode label18 The branch calculation is: pc + (4*label24) where label24 is the concatenation of label6 and label18. */ /* Grab the instruction. */ insn = bfd_get_32 (input_bfd, contents + rello->r_offset); value -= input_section->output_section->vma + input_section->output_offset; value -= rello->r_offset; value += rello->r_addend; value = value >> 2; label6 = value & 0xfc0000; label6 = label6 << 7; label18 = value & 0x3ffff; insn = insn & 0x803c0000; insn = insn | label6; insn = insn | label18; bfd_put_32 (input_bfd, insn, contents + rello->r_offset); return bfd_reloc_ok; } static bfd_reloc_status_type elf32_frv_relocate_gprelhi (info, input_bfd, input_section, relocation, contents, value) struct bfd_link_info *info; bfd *input_bfd; asection *input_section; Elf_Internal_Rela *relocation; bfd_byte *contents; bfd_vma value; { bfd_vma insn; bfd_vma gp; struct bfd_link_hash_entry *h; h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE); gp = (h->u.def.value + h->u.def.section->output_section->vma + h->u.def.section->output_offset); value -= input_section->output_section->vma; value -= (gp - input_section->output_section->vma); value += relocation->r_addend; value = ((value >> 16) & 0xffff); if ((long) value > 0xffff || (long) value < -0x10000) return bfd_reloc_overflow; insn = bfd_get_32 (input_bfd, contents + relocation->r_offset); insn = (insn & 0xffff0000) | value; bfd_put_32 (input_bfd, insn, contents + relocation->r_offset); return bfd_reloc_ok; } static bfd_reloc_status_type elf32_frv_relocate_gprello (info, input_bfd, input_section, relocation, contents, value) struct bfd_link_info *info; bfd *input_bfd; asection *input_section; Elf_Internal_Rela *relocation; bfd_byte *contents; bfd_vma value; { bfd_vma insn; bfd_vma gp; struct bfd_link_hash_entry *h; h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE); gp = (h->u.def.value + h->u.def.section->output_section->vma + h->u.def.section->output_offset); value -= input_section->output_section->vma; value -= (gp - input_section->output_section->vma); value += relocation->r_addend; value = value & 0xffff; if ((long) value > 0xffff || (long) value < -0x10000) return bfd_reloc_overflow; insn = bfd_get_32 (input_bfd, contents + relocation->r_offset); insn = (insn & 0xffff0000) | value; bfd_put_32 (input_bfd, insn, contents + relocation->r_offset); return bfd_reloc_ok; } static reloc_howto_type * frv_reloc_type_lookup (abfd, code) bfd *abfd ATTRIBUTE_UNUSED; bfd_reloc_code_real_type code; { switch (code) { default: break; case BFD_RELOC_NONE: return &elf32_frv_howto_table[ (int) R_FRV_NONE]; case BFD_RELOC_32: if (elf_elfheader (abfd)->e_type == ET_EXEC || elf_elfheader (abfd)->e_type == ET_DYN) return &elf32_frv_rel_32_howto; /* Fall through. */ case BFD_RELOC_CTOR: return &elf32_frv_howto_table[ (int) R_FRV_32]; case BFD_RELOC_FRV_LABEL16: return &elf32_frv_howto_table[ (int) R_FRV_LABEL16]; case BFD_RELOC_FRV_LABEL24: return &elf32_frv_howto_table[ (int) R_FRV_LABEL24]; case BFD_RELOC_FRV_LO16: return &elf32_frv_howto_table[ (int) R_FRV_LO16]; case BFD_RELOC_FRV_HI16: return &elf32_frv_howto_table[ (int) R_FRV_HI16]; case BFD_RELOC_FRV_GPREL12: return &elf32_frv_howto_table[ (int) R_FRV_GPREL12]; case BFD_RELOC_FRV_GPRELU12: return &elf32_frv_howto_table[ (int) R_FRV_GPRELU12]; case BFD_RELOC_FRV_GPREL32: return &elf32_frv_howto_table[ (int) R_FRV_GPREL32]; case BFD_RELOC_FRV_GPRELHI: return &elf32_frv_howto_table[ (int) R_FRV_GPRELHI]; case BFD_RELOC_FRV_GPRELLO: return &elf32_frv_howto_table[ (int) R_FRV_GPRELLO]; case BFD_RELOC_FRV_GOT12: return &elf32_frv_howto_table[ (int) R_FRV_GOT12]; case BFD_RELOC_FRV_GOTHI: return &elf32_frv_howto_table[ (int) R_FRV_GOTHI]; case BFD_RELOC_FRV_GOTLO: return &elf32_frv_howto_table[ (int) R_FRV_GOTLO]; case BFD_RELOC_FRV_FUNCDESC: if (elf_elfheader (abfd)->e_type == ET_EXEC || elf_elfheader (abfd)->e_type == ET_DYN) return &elf32_frv_rel_funcdesc_howto; return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC]; case BFD_RELOC_FRV_FUNCDESC_GOT12: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOT12]; case BFD_RELOC_FRV_FUNCDESC_GOTHI: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOTHI]; case BFD_RELOC_FRV_FUNCDESC_GOTLO: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOTLO]; case BFD_RELOC_FRV_FUNCDESC_VALUE: if (elf_elfheader (abfd)->e_type == ET_EXEC || elf_elfheader (abfd)->e_type == ET_DYN) return &elf32_frv_rel_funcdesc_value_howto; return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_VALUE]; case BFD_RELOC_FRV_FUNCDESC_GOTOFF12: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOTOFF12]; case BFD_RELOC_FRV_FUNCDESC_GOTOFFHI: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOTOFFHI]; case BFD_RELOC_FRV_FUNCDESC_GOTOFFLO: return &elf32_frv_howto_table[ (int) R_FRV_FUNCDESC_GOTOFFLO]; case BFD_RELOC_FRV_GOTOFF12: return &elf32_frv_howto_table[ (int) R_FRV_GOTOFF12]; case BFD_RELOC_FRV_GOTOFFHI: return &elf32_frv_howto_table[ (int) R_FRV_GOTOFFHI]; case BFD_RELOC_FRV_GOTOFFLO: return &elf32_frv_howto_table[ (int) R_FRV_GOTOFFLO]; case BFD_RELOC_FRV_GETTLSOFF: return &elf32_frv_howto_table[ (int) R_FRV_GETTLSOFF]; case BFD_RELOC_FRV_TLSDESC_VALUE: if (elf_elfheader (abfd)->e_type == ET_EXEC || elf_elfheader (abfd)->e_type == ET_DYN) return &elf32_frv_rel_tlsdesc_value_howto; return &elf32_frv_howto_table[ (int) R_FRV_TLSDESC_VALUE]; case BFD_RELOC_FRV_GOTTLSDESC12: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSDESC12]; case BFD_RELOC_FRV_GOTTLSDESCHI: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSDESCHI]; case BFD_RELOC_FRV_GOTTLSDESCLO: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSDESCLO]; case BFD_RELOC_FRV_TLSMOFF12: return &elf32_frv_howto_table[ (int) R_FRV_TLSMOFF12]; case BFD_RELOC_FRV_TLSMOFFHI: return &elf32_frv_howto_table[ (int) R_FRV_TLSMOFFHI]; case BFD_RELOC_FRV_TLSMOFFLO: return &elf32_frv_howto_table[ (int) R_FRV_TLSMOFFLO]; case BFD_RELOC_FRV_GOTTLSOFF12: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSOFF12]; case BFD_RELOC_FRV_GOTTLSOFFHI: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSOFFHI]; case BFD_RELOC_FRV_GOTTLSOFFLO: return &elf32_frv_howto_table[ (int) R_FRV_GOTTLSOFFLO]; case BFD_RELOC_FRV_TLSOFF: if (elf_elfheader (abfd)->e_type == ET_EXEC || elf_elfheader (abfd)->e_type == ET_DYN) return &elf32_frv_rel_tlsoff_howto; return &elf32_frv_howto_table[ (int) R_FRV_TLSOFF]; case BFD_RELOC_FRV_TLSDESC_RELAX: return &elf32_frv_howto_table[ (int) R_FRV_TLSDESC_RELAX]; case BFD_RELOC_FRV_GETTLSOFF_RELAX: return &elf32_frv_howto_table[ (int) R_FRV_GETTLSOFF_RELAX]; case BFD_RELOC_FRV_TLSOFF_RELAX: return &elf32_frv_howto_table[ (int) R_FRV_TLSOFF_RELAX]; case BFD_RELOC_FRV_TLSMOFF: return &elf32_frv_howto_table[ (int) R_FRV_TLSMOFF]; case BFD_RELOC_VTABLE_INHERIT: return &elf32_frv_vtinherit_howto; case BFD_RELOC_VTABLE_ENTRY: return &elf32_frv_vtentry_howto; } return NULL; } static reloc_howto_type * frv_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED, const char *r_name) { unsigned int i; for (i = 0; i < sizeof (elf32_frv_howto_table) / sizeof (elf32_frv_howto_table[0]); i++) if (elf32_frv_howto_table[i].name != NULL && strcasecmp (elf32_frv_howto_table[i].name, r_name) == 0) return &elf32_frv_howto_table[i]; if (strcasecmp (elf32_frv_vtinherit_howto.name, r_name) == 0) return &elf32_frv_vtinherit_howto; if (strcasecmp (elf32_frv_vtentry_howto.name, r_name) == 0) return &elf32_frv_vtentry_howto; return NULL; } /* Set the howto pointer for an FRV ELF reloc. */ static void frv_info_to_howto_rela (abfd, cache_ptr, dst) bfd *abfd ATTRIBUTE_UNUSED; arelent *cache_ptr; Elf_Internal_Rela *dst; { unsigned int r_type; r_type = ELF32_R_TYPE (dst->r_info); switch (r_type) { case R_FRV_GNU_VTINHERIT: cache_ptr->howto = &elf32_frv_vtinherit_howto; break; case R_FRV_GNU_VTENTRY: cache_ptr->howto = &elf32_frv_vtentry_howto; break; default: cache_ptr->howto = & elf32_frv_howto_table [r_type]; break; } } /* Set the howto pointer for an FRV ELF REL reloc. */ static void frvfdpic_info_to_howto_rel (bfd *abfd ATTRIBUTE_UNUSED, arelent *cache_ptr, Elf_Internal_Rela *dst) { unsigned int r_type; r_type = ELF32_R_TYPE (dst->r_info); switch (r_type) { case R_FRV_32: cache_ptr->howto = &elf32_frv_rel_32_howto; break; case R_FRV_FUNCDESC: cache_ptr->howto = &elf32_frv_rel_funcdesc_howto; break; case R_FRV_FUNCDESC_VALUE: cache_ptr->howto = &elf32_frv_rel_funcdesc_value_howto; break; case R_FRV_TLSDESC_VALUE: cache_ptr->howto = &elf32_frv_rel_tlsdesc_value_howto; break; case R_FRV_TLSOFF: cache_ptr->howto = &elf32_frv_rel_tlsoff_howto; break; default: cache_ptr->howto = NULL; break; } } /* Perform a single relocation. By default we use the standard BFD routines, but a few relocs, we have to do them ourselves. */ static bfd_reloc_status_type frv_final_link_relocate (howto, input_bfd, input_section, contents, rel, relocation) reloc_howto_type *howto; bfd *input_bfd; asection *input_section; bfd_byte *contents; Elf_Internal_Rela *rel; bfd_vma relocation; { return _bfd_final_link_relocate (howto, input_bfd, input_section, contents, rel->r_offset, relocation, rel->r_addend); } /* Relocate an FRV ELF section. The RELOCATE_SECTION function is called by the new ELF backend linker to handle the relocations for a section. The relocs are always passed as Rela structures; if the section actually uses Rel structures, the r_addend field will always be zero. This function is responsible for adjusting the section contents as necessary, and (if using Rela relocs and generating a relocatable output file) adjusting the reloc addend as necessary. This function does not have to worry about setting the reloc address or the reloc symbol index. LOCAL_SYMS is a pointer to the swapped in local symbols. LOCAL_SECTIONS is an array giving the section in the input file corresponding to the st_shndx field of each local symbol. The global hash table entry for the global symbols can be found via elf_sym_hashes (input_bfd). When generating relocatable output, this function must handle STB_LOCAL/STT_SECTION symbols specially. The output symbol is going to be the section symbol corresponding to the output section, which means that the addend must be adjusted accordingly. */ static bfd_boolean elf32_frv_relocate_section (output_bfd, info, input_bfd, input_section, contents, relocs, local_syms, local_sections) bfd *output_bfd ATTRIBUTE_UNUSED; struct bfd_link_info *info; bfd *input_bfd; asection *input_section; bfd_byte *contents; Elf_Internal_Rela *relocs; Elf_Internal_Sym *local_syms; asection **local_sections; { Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; Elf_Internal_Rela *rel; Elf_Internal_Rela *relend; unsigned isec_segment, got_segment, plt_segment, gprel_segment, tls_segment, check_segment[2]; int silence_segment_error = !(info->shared || info->pie); unsigned long insn; symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr; sym_hashes = elf_sym_hashes (input_bfd); relend = relocs + input_section->reloc_count; isec_segment = _frvfdpic_osec_to_segment (output_bfd, input_section->output_section); if (IS_FDPIC (output_bfd) && frvfdpic_got_section (info)) got_segment = _frvfdpic_osec_to_segment (output_bfd, frvfdpic_got_section (info) ->output_section); else got_segment = -1; if (IS_FDPIC (output_bfd) && frvfdpic_gotfixup_section (info)) gprel_segment = _frvfdpic_osec_to_segment (output_bfd, frvfdpic_gotfixup_section (info) ->output_section); else gprel_segment = -1; if (IS_FDPIC (output_bfd) && frvfdpic_plt_section (info)) plt_segment = _frvfdpic_osec_to_segment (output_bfd, frvfdpic_plt_section (info) ->output_section); else plt_segment = -1; if (elf_hash_table (info)->tls_sec) tls_segment = _frvfdpic_osec_to_segment (output_bfd, elf_hash_table (info)->tls_sec); else tls_segment = -1; for (rel = relocs; rel < relend; rel ++) { reloc_howto_type *howto; unsigned long r_symndx; Elf_Internal_Sym *sym; asection *sec; struct elf_link_hash_entry *h; bfd_vma relocation; bfd_reloc_status_type r; const char *name; int r_type; asection *osec; struct frvfdpic_relocs_info *picrel; bfd_vma orig_addend = rel->r_addend; r_type = ELF32_R_TYPE (rel->r_info); if ( r_type == R_FRV_GNU_VTINHERIT || r_type == R_FRV_GNU_VTENTRY) continue; r_symndx = ELF32_R_SYM (rel->r_info); howto = elf32_frv_howto_table + ELF32_R_TYPE (rel->r_info); h = NULL; sym = NULL; sec = NULL; if (r_symndx < symtab_hdr->sh_info) { sym = local_syms + r_symndx; osec = sec = local_sections [r_symndx]; relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel); name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link, sym->st_name); if (name == NULL || name[0] == 0) name = bfd_section_name (input_bfd, sec); } else { bfd_boolean warned; bfd_boolean unresolved_reloc; RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel, r_symndx, symtab_hdr, sym_hashes, h, sec, relocation, unresolved_reloc, warned); osec = sec; name = h->root.root.string; } if (sec != NULL && elf_discarded_section (sec)) RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section, rel, relend, howto, contents); if (info->relocatable) continue; if (r_type != R_FRV_TLSMOFF && h != NULL && (h->root.type == bfd_link_hash_defined || h->root.type == bfd_link_hash_defweak) && !FRVFDPIC_SYM_LOCAL (info, h)) { osec = sec = NULL; relocation = 0; } switch (r_type) { case R_FRV_LABEL24: case R_FRV_32: if (! IS_FDPIC (output_bfd)) goto non_fdpic; case R_FRV_GOT12: case R_FRV_GOTHI: case R_FRV_GOTLO: case R_FRV_FUNCDESC_GOT12: case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTLO: case R_FRV_GOTOFF12: case R_FRV_GOTOFFHI: case R_FRV_GOTOFFLO: case R_FRV_FUNCDESC_GOTOFF12: case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_FUNCDESC_GOTOFFLO: case R_FRV_FUNCDESC: case R_FRV_FUNCDESC_VALUE: case R_FRV_GETTLSOFF: case R_FRV_TLSDESC_VALUE: case R_FRV_GOTTLSDESC12: case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: case R_FRV_TLSMOFF12: case R_FRV_TLSMOFFHI: case R_FRV_TLSMOFFLO: case R_FRV_GOTTLSOFF12: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: case R_FRV_TLSOFF: case R_FRV_TLSDESC_RELAX: case R_FRV_GETTLSOFF_RELAX: case R_FRV_TLSOFF_RELAX: case R_FRV_TLSMOFF: if (h != NULL) picrel = frvfdpic_relocs_info_for_global (frvfdpic_relocs_info (info), input_bfd, h, orig_addend, INSERT); else /* In order to find the entry we created before, we must use the original addend, not the one that may have been modified by _bfd_elf_rela_local_sym(). */ picrel = frvfdpic_relocs_info_for_local (frvfdpic_relocs_info (info), input_bfd, r_symndx, orig_addend, INSERT); if (! picrel) return FALSE; if (!_frvfdpic_emit_got_relocs_plt_entries (picrel, output_bfd, info, osec, sym, rel->r_addend)) { (*_bfd_error_handler) (_("%B(%A+0x%x): relocation to `%s+%x' may have caused the error above"), input_bfd, input_section, rel->r_offset, name, rel->r_addend); return FALSE; } break; default: non_fdpic: picrel = NULL; if (h && ! FRVFDPIC_SYM_LOCAL (info, h)) { info->callbacks->warning (info, _("relocation references symbol not defined in the module"), name, input_bfd, input_section, rel->r_offset); return FALSE; } break; } switch (r_type) { case R_FRV_GETTLSOFF: case R_FRV_TLSDESC_VALUE: case R_FRV_GOTTLSDESC12: case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: case R_FRV_TLSMOFF12: case R_FRV_TLSMOFFHI: case R_FRV_TLSMOFFLO: case R_FRV_GOTTLSOFF12: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: case R_FRV_TLSOFF: case R_FRV_TLSDESC_RELAX: case R_FRV_GETTLSOFF_RELAX: case R_FRV_TLSOFF_RELAX: case R_FRV_TLSMOFF: if (sec && (bfd_is_abs_section (sec) || bfd_is_und_section (sec))) relocation += tls_biased_base (info); break; default: break; } /* Try to apply TLS relaxations. */ if (1) switch (r_type) { #define LOCAL_EXEC_P(info, picrel) \ ((info)->executable \ && (picrel->symndx != -1 || FRVFDPIC_SYM_LOCAL ((info), (picrel)->d.h))) #define INITIAL_EXEC_P(info, picrel) \ (((info)->executable || (info)->flags & DF_STATIC_TLS) \ && (picrel)->tlsoff_entry) #define IN_RANGE_FOR_OFST12_P(value) \ ((bfd_vma)((value) + 2048) < (bfd_vma)4096) #define IN_RANGE_FOR_SETLOS_P(value) \ ((bfd_vma)((value) + 32768) < (bfd_vma)65536) #define TLSMOFF_IN_RANGE_FOR_SETLOS_P(value, info) \ (IN_RANGE_FOR_SETLOS_P ((value) - tls_biased_base (info))) #define RELAX_GETTLSOFF_LOCAL_EXEC_P(info, picrel, value) \ (LOCAL_EXEC_P ((info), (picrel)) \ && TLSMOFF_IN_RANGE_FOR_SETLOS_P((value), (info))) #define RELAX_GETTLSOFF_INITIAL_EXEC_P(info, picrel) \ (INITIAL_EXEC_P ((info), (picrel)) \ && IN_RANGE_FOR_OFST12_P ((picrel)->tlsoff_entry)) #define RELAX_TLSDESC_LOCAL_EXEC_P(info, picrel, value) \ (LOCAL_EXEC_P ((info), (picrel))) #define RELAX_TLSDESC_INITIAL_EXEC_P(info, picrel) \ (INITIAL_EXEC_P ((info), (picrel))) #define RELAX_GOTTLSOFF_LOCAL_EXEC_P(info, picrel, value) \ (LOCAL_EXEC_P ((info), (picrel)) \ && TLSMOFF_IN_RANGE_FOR_SETLOS_P((value), (info))) case R_FRV_GETTLSOFF: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a call instruction? */ if ((insn & (unsigned long)0x01fc0000) != 0x003c0000) { r = info->callbacks->warning (info, _("R_FRV_GETTLSOFF not applied to a call instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_GETTLSOFF_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace the call instruction (except the packing bit) with setlos #tlsmofflo(symbol+offset), gr9. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x12fc0000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_GETTLSOFF_INITIAL_EXEC_P (info, picrel)) { /* Replace the call instruction (except the packing bit) with ldi @(gr15, #gottlsoff12(symbol+addend)), gr9. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x12c8f000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_GOTTLSOFF12; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_GOTTLSDESC12: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this an lddi instruction? */ if ((insn & (unsigned long)0x01fc0000) != 0x00cc0000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSDESC12 not applied to an lddi instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) && TLSMOFF_IN_RANGE_FOR_SETLOS_P (relocation + rel->r_addend, info)) { /* Replace lddi @(grB, #gottlsdesc12(symbol+offset), grC with setlos #tlsmofflo(symbol+offset), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x80000000) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); insn |= (unsigned long)0x00fc0000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace lddi @(grB, #gottlsdesc12(symbol+offset), grC with sethi #tlsmoffhi(symbol+offset), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x80000000) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); insn |= (unsigned long)0x00f80000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFHI; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel)) { /* Replace lddi @(grB, #gottlsdesc12(symbol+offset), grC with ldi @(grB, #gottlsoff12(symbol+offset), gr<C+1>. Preserve the packing bit. If gottlsoff12 overflows, we'll error out, but that's sort-of ok, since we'd started with gottlsdesc12, that's actually more demanding. Compiling with -fPIE instead of -fpie would fix it; linking with --relax should fix it as well. */ insn = (insn & (unsigned long)0x80cbf000) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_GOTTLSOFF12; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_GOTTLSDESCHI: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a sethi instruction? */ if ((insn & (unsigned long)0x01ff0000) != 0x00f80000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSDESCHI not applied to a sethi instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) || (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_SETLOS_P (picrel->tlsoff_entry))) { /* Replace sethi with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel)) { /* Simply decay GOTTLSDESC to GOTTLSOFF. */ r_type = R_FRV_GOTTLSOFFHI; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_GOTTLSDESCLO: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a setlo or setlos instruction? */ if ((insn & (unsigned long)0x01f70000) != 0x00f40000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSDESCLO" " not applied to a setlo or setlos instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) || (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_OFST12_P (picrel->tlsoff_entry))) { /* Replace setlo/setlos with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel)) { /* If the corresponding sethi (if it exists) decayed to a nop, make sure this becomes (or already is) a setlos, not setlo. */ if (IN_RANGE_FOR_SETLOS_P (picrel->tlsoff_entry)) { insn |= (unsigned long)0x00080000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); } /* Simply decay GOTTLSDESC to GOTTLSOFF. */ r_type = R_FRV_GOTTLSOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_TLSDESC_RELAX: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this an ldd instruction? */ if ((insn & (unsigned long)0x01fc0fc0) != 0x00080140) { r = info->callbacks->warning (info, _("R_FRV_TLSDESC_RELAX not applied to an ldd instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) && TLSMOFF_IN_RANGE_FOR_SETLOS_P (relocation + rel->r_addend, info)) { /* Replace ldd #tlsdesc(symbol+offset)@(grB, grA), grC with setlos #tlsmofflo(symbol+offset), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x80000000) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); insn |= (unsigned long)0x00fc0000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace ldd #tlsdesc(symbol+offset)@(grB, grA), grC with sethi #tlsmoffhi(symbol+offset), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x80000000) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); insn |= (unsigned long)0x00f80000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFHI; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_OFST12_P (picrel->tlsoff_entry)) { /* Replace ldd #tlsdesc(symbol+offset)@(grB, grA), grC with ldi @(grB, #gottlsoff12(symbol+offset), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x8003f000) | (unsigned long)0x00c80000 | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_GOTTLSOFF12; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel)) { /* Replace ldd #tlsdesc(symbol+offset)@(grB, grA), grC with ld #tlsoff(symbol+offset)@(grB, grA), gr<C+1>. Preserve the packing bit. */ insn = (insn & (unsigned long)0x81ffffbf) | ((insn + (unsigned long)0x02000000) & (unsigned long)0x7e000000); bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* #tlsoff(symbol+offset) is just a relaxation annotation, so there's nothing left to relocate. */ continue; } break; case R_FRV_GETTLSOFF_RELAX: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a calll or callil instruction? */ if ((insn & (unsigned long)0x7ff80fc0) != 0x02300000) { r = info->callbacks->warning (info, _("R_FRV_GETTLSOFF_RELAX" " not applied to a calll instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) && TLSMOFF_IN_RANGE_FOR_SETLOS_P (relocation + rel->r_addend, info)) { /* Replace calll with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } else if (RELAX_TLSDESC_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace calll with setlo #tlsmofflo(symbol+offset), gr9. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x12f40000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel)) { /* Replace calll with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } break; case R_FRV_GOTTLSOFF12: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this an ldi instruction? */ if ((insn & (unsigned long)0x01fc0000) != 0x00c80000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSOFF12 not applied to an ldi instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_GOTTLSOFF_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace ldi @(grB, #gottlsoff12(symbol+offset), grC with setlos #tlsmofflo(symbol+offset), grC. Preserve the packing bit. */ insn &= (unsigned long)0xfe000000; insn |= (unsigned long)0x00fc0000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_GOTTLSOFFHI: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a sethi instruction? */ if ((insn & (unsigned long)0x01ff0000) != 0x00f80000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSOFFHI not applied to a sethi instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_GOTTLSOFF_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) || (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_OFST12_P (picrel->tlsoff_entry))) { /* Replace sethi with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } break; case R_FRV_GOTTLSOFFLO: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a setlo or setlos instruction? */ if ((insn & (unsigned long)0x01f70000) != 0x00f40000) { r = info->callbacks->warning (info, _("R_FRV_GOTTLSOFFLO" " not applied to a setlo or setlos instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_GOTTLSOFF_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend) || (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_OFST12_P (picrel->tlsoff_entry))) { /* Replace setlo/setlos with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } break; case R_FRV_TLSOFF_RELAX: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this an ld instruction? */ if ((insn & (unsigned long)0x01fc0fc0) != 0x00080100) { r = info->callbacks->warning (info, _("R_FRV_TLSOFF_RELAX not applied to an ld instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (RELAX_GOTTLSOFF_LOCAL_EXEC_P (info, picrel, relocation + rel->r_addend)) { /* Replace ld #gottlsoff(symbol+offset)@(grB, grA), grC with setlos #tlsmofflo(symbol+offset), grC. Preserve the packing bit. */ insn &= (unsigned long)0xfe000000; insn |= (unsigned long)0x00fc0000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_TLSMOFFLO; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } else if (RELAX_TLSDESC_INITIAL_EXEC_P (info, picrel) && IN_RANGE_FOR_OFST12_P (picrel->tlsoff_entry)) { /* Replace ld #tlsoff(symbol+offset)@(grB, grA), grC with ldi @(grB, #gottlsoff12(symbol+offset), grC. Preserve the packing bit. */ insn = (insn & (unsigned long)0xfe03f000) | (unsigned long)0x00c80000;; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); r_type = R_FRV_GOTTLSOFF12; howto = elf32_frv_howto_table + r_type; rel->r_info = ELF32_R_INFO (r_symndx, r_type); } break; case R_FRV_TLSMOFFHI: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a sethi instruction? */ if ((insn & (unsigned long)0x01ff0000) != 0x00f80000) { r = info->callbacks->warning (info, _("R_FRV_TLSMOFFHI not applied to a sethi instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (TLSMOFF_IN_RANGE_FOR_SETLOS_P (relocation + rel->r_addend, info)) { /* Replace sethi with a nop. Preserve the packing bit. */ insn &= (unsigned long)0x80000000; insn |= (unsigned long)0x00880000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); /* Nothing to relocate. */ continue; } break; case R_FRV_TLSMOFFLO: insn = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Is this a setlo or setlos instruction? */ if ((insn & (unsigned long)0x01f70000) != 0x00f40000) { r = info->callbacks->warning (info, _("R_FRV_TLSMOFFLO" " not applied to a setlo or setlos instruction"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (TLSMOFF_IN_RANGE_FOR_SETLOS_P (relocation + rel->r_addend, info)) /* If the corresponding sethi (if it exists) decayed to a nop, make sure this becomes (or already is) a setlos, not setlo. */ { insn |= (unsigned long)0x00080000; bfd_put_32 (input_bfd, insn, contents + rel->r_offset); } break; /* There's nothing to relax in these: R_FRV_TLSDESC_VALUE R_FRV_TLSOFF R_FRV_TLSMOFF12 R_FRV_TLSMOFFHI R_FRV_TLSMOFFLO R_FRV_TLSMOFF */ default: break; } switch (r_type) { case R_FRV_LABEL24: check_segment[0] = isec_segment; if (! IS_FDPIC (output_bfd)) check_segment[1] = isec_segment; else if (picrel->plt) { relocation = frvfdpic_plt_section (info)->output_section->vma + frvfdpic_plt_section (info)->output_offset + picrel->plt_entry; check_segment[1] = plt_segment; } /* We don't want to warn on calls to undefined weak symbols, as calls to them must be protected by non-NULL tests anyway, and unprotected calls would invoke undefined behavior. */ else if (picrel->symndx == -1 && picrel->d.h->root.type == bfd_link_hash_undefweak) check_segment[1] = check_segment[0]; else check_segment[1] = sec ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : (unsigned)-1; break; case R_FRV_GOT12: case R_FRV_GOTHI: case R_FRV_GOTLO: relocation = picrel->got_entry; check_segment[0] = check_segment[1] = got_segment; break; case R_FRV_FUNCDESC_GOT12: case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTLO: relocation = picrel->fdgot_entry; check_segment[0] = check_segment[1] = got_segment; break; case R_FRV_GOTOFFHI: case R_FRV_GOTOFF12: case R_FRV_GOTOFFLO: relocation -= frvfdpic_got_section (info)->output_section->vma + frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info); check_segment[0] = got_segment; check_segment[1] = sec ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : (unsigned)-1; break; case R_FRV_FUNCDESC_GOTOFF12: case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_FUNCDESC_GOTOFFLO: relocation = picrel->fd_entry; check_segment[0] = check_segment[1] = got_segment; break; case R_FRV_FUNCDESC: { int dynindx; bfd_vma addend = rel->r_addend; if (! (h && h->root.type == bfd_link_hash_undefweak && FRVFDPIC_SYM_LOCAL (info, h))) { /* If the symbol is dynamic and there may be dynamic symbol resolution because we are or are linked with a shared library, emit a FUNCDESC relocation such that the dynamic linker will allocate the function descriptor. If the symbol needs a non-local function descriptor but binds locally (e.g., its visibility is protected, emit a dynamic relocation decayed to section+offset. */ if (h && ! FRVFDPIC_FUNCDESC_LOCAL (info, h) && FRVFDPIC_SYM_LOCAL (info, h) && !(info->executable && !info->pie)) { dynindx = elf_section_data (h->root.u.def.section ->output_section)->dynindx; addend += h->root.u.def.section->output_offset + h->root.u.def.value; } else if (h && ! FRVFDPIC_FUNCDESC_LOCAL (info, h)) { if (addend) { info->callbacks->warning (info, _("R_FRV_FUNCDESC references dynamic symbol with nonzero addend"), name, input_bfd, input_section, rel->r_offset); return FALSE; } dynindx = h->dynindx; } else { /* Otherwise, we know we have a private function descriptor, so reference it directly. */ BFD_ASSERT (picrel->privfd); r_type = R_FRV_32; dynindx = elf_section_data (frvfdpic_got_section (info) ->output_section)->dynindx; addend = frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info) + picrel->fd_entry; } /* If there is room for dynamic symbol resolution, emit the dynamic relocation. However, if we're linking an executable at a fixed location, we won't have emitted a dynamic symbol entry for the got section, so idx will be zero, which means we can and should compute the address of the private descriptor ourselves. */ if (info->executable && !info->pie && (!h || FRVFDPIC_FUNCDESC_LOCAL (info, h))) { addend += frvfdpic_got_section (info)->output_section->vma; if ((bfd_get_section_flags (output_bfd, input_section->output_section) & (SEC_ALLOC | SEC_LOAD)) == (SEC_ALLOC | SEC_LOAD)) { bfd_vma offset; if (_frvfdpic_osec_readonly_p (output_bfd, input_section ->output_section)) { info->callbacks->warning (info, _("cannot emit fixups in read-only section"), name, input_bfd, input_section, rel->r_offset); return FALSE; } offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel->r_offset); if (offset != (bfd_vma)-1) _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), offset + input_section ->output_section->vma + input_section->output_offset, picrel); } } else if ((bfd_get_section_flags (output_bfd, input_section->output_section) & (SEC_ALLOC | SEC_LOAD)) == (SEC_ALLOC | SEC_LOAD)) { bfd_vma offset; if (_frvfdpic_osec_readonly_p (output_bfd, input_section ->output_section)) { info->callbacks->warning (info, _("cannot emit dynamic relocations in read-only section"), name, input_bfd, input_section, rel->r_offset); return FALSE; } offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel->r_offset); if (offset != (bfd_vma)-1) _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), offset + input_section ->output_section->vma + input_section->output_offset, r_type, dynindx, addend, picrel); } else addend += frvfdpic_got_section (info)->output_section->vma; } /* We want the addend in-place because dynamic relocations are REL. Setting relocation to it should arrange for it to be installed. */ relocation = addend - rel->r_addend; } check_segment[0] = check_segment[1] = got_segment; break; case R_FRV_32: if (! IS_FDPIC (output_bfd)) { check_segment[0] = check_segment[1] = -1; break; } /* Fall through. */ case R_FRV_FUNCDESC_VALUE: { int dynindx; bfd_vma addend = rel->r_addend; /* If the symbol is dynamic but binds locally, use section+offset. */ if (h && ! FRVFDPIC_SYM_LOCAL (info, h)) { if (addend && r_type == R_FRV_FUNCDESC_VALUE) { info->callbacks->warning (info, _("R_FRV_FUNCDESC_VALUE references dynamic symbol with nonzero addend"), name, input_bfd, input_section, rel->r_offset); return FALSE; } dynindx = h->dynindx; } else { if (h) addend += h->root.u.def.value; else addend += sym->st_value; if (osec) addend += osec->output_offset; if (osec && osec->output_section && ! bfd_is_abs_section (osec->output_section) && ! bfd_is_und_section (osec->output_section)) dynindx = elf_section_data (osec->output_section)->dynindx; else dynindx = 0; } /* If we're linking an executable at a fixed address, we can omit the dynamic relocation as long as the symbol is defined in the current link unit (which is implied by its output section not being NULL). */ if (info->executable && !info->pie && (!h || FRVFDPIC_SYM_LOCAL (info, h))) { if (osec) addend += osec->output_section->vma; if (IS_FDPIC (input_bfd) && (bfd_get_section_flags (output_bfd, input_section->output_section) & (SEC_ALLOC | SEC_LOAD)) == (SEC_ALLOC | SEC_LOAD)) { if (_frvfdpic_osec_readonly_p (output_bfd, input_section ->output_section)) { info->callbacks->warning (info, _("cannot emit fixups in read-only section"), name, input_bfd, input_section, rel->r_offset); return FALSE; } if (!h || h->root.type != bfd_link_hash_undefweak) { bfd_vma offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel->r_offset); if (offset != (bfd_vma)-1) { _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), offset + input_section ->output_section->vma + input_section->output_offset, picrel); if (r_type == R_FRV_FUNCDESC_VALUE) _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), offset + input_section->output_section->vma + input_section->output_offset + 4, picrel); } } } } else { if ((bfd_get_section_flags (output_bfd, input_section->output_section) & (SEC_ALLOC | SEC_LOAD)) == (SEC_ALLOC | SEC_LOAD)) { bfd_vma offset; if (_frvfdpic_osec_readonly_p (output_bfd, input_section ->output_section)) { info->callbacks->warning (info, _("cannot emit dynamic relocations in read-only section"), name, input_bfd, input_section, rel->r_offset); return FALSE; } offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel->r_offset); if (offset != (bfd_vma)-1) _frvfdpic_add_dyn_reloc (output_bfd, frvfdpic_gotrel_section (info), offset + input_section ->output_section->vma + input_section->output_offset, r_type, dynindx, addend, picrel); } else if (osec) addend += osec->output_section->vma; /* We want the addend in-place because dynamic relocations are REL. Setting relocation to it should arrange for it to be installed. */ relocation = addend - rel->r_addend; } if (r_type == R_FRV_FUNCDESC_VALUE) { /* If we've omitted the dynamic relocation, just emit the fixed addresses of the symbol and of the local GOT base offset. */ if (info->executable && !info->pie && (!h || FRVFDPIC_SYM_LOCAL (info, h))) bfd_put_32 (output_bfd, frvfdpic_got_section (info)->output_section->vma + frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info), contents + rel->r_offset + 4); else /* A function descriptor used for lazy or local resolving is initialized such that its high word contains the output section index in which the PLT entries are located, and the low word contains the offset of the lazy PLT entry entry point into that section. */ bfd_put_32 (output_bfd, h && ! FRVFDPIC_SYM_LOCAL (info, h) ? 0 : _frvfdpic_osec_to_segment (output_bfd, sec ->output_section), contents + rel->r_offset + 4); } } check_segment[0] = check_segment[1] = got_segment; break; case R_FRV_GPREL12: case R_FRV_GPRELU12: case R_FRV_GPREL32: case R_FRV_GPRELHI: case R_FRV_GPRELLO: check_segment[0] = gprel_segment; check_segment[1] = sec ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : (unsigned)-1; break; case R_FRV_GETTLSOFF: relocation = frvfdpic_plt_section (info)->output_section->vma + frvfdpic_plt_section (info)->output_offset + picrel->tlsplt_entry; BFD_ASSERT (picrel->tlsplt_entry != (bfd_vma)-1 && picrel->tlsdesc_entry); check_segment[0] = isec_segment; check_segment[1] = plt_segment; break; case R_FRV_GOTTLSDESC12: case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: BFD_ASSERT (picrel->tlsdesc_entry); relocation = picrel->tlsdesc_entry; check_segment[0] = tls_segment; check_segment[1] = sec && ! bfd_is_abs_section (sec) && ! bfd_is_und_section (sec) ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : tls_segment; break; case R_FRV_TLSMOFF12: case R_FRV_TLSMOFFHI: case R_FRV_TLSMOFFLO: case R_FRV_TLSMOFF: check_segment[0] = tls_segment; if (! sec) check_segment[1] = -1; else if (bfd_is_abs_section (sec) || bfd_is_und_section (sec)) { relocation = 0; check_segment[1] = tls_segment; } else if (sec->output_section) { relocation -= tls_biased_base (info); check_segment[1] = _frvfdpic_osec_to_segment (output_bfd, sec->output_section); } else check_segment[1] = -1; break; case R_FRV_GOTTLSOFF12: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: BFD_ASSERT (picrel->tlsoff_entry); relocation = picrel->tlsoff_entry; check_segment[0] = tls_segment; check_segment[1] = sec && ! bfd_is_abs_section (sec) && ! bfd_is_und_section (sec) ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : tls_segment; break; case R_FRV_TLSDESC_VALUE: case R_FRV_TLSOFF: /* These shouldn't be present in input object files. */ check_segment[0] = check_segment[1] = isec_segment; break; case R_FRV_TLSDESC_RELAX: case R_FRV_GETTLSOFF_RELAX: case R_FRV_TLSOFF_RELAX: /* These are just annotations for relaxation, nothing to do here. */ continue; default: check_segment[0] = isec_segment; check_segment[1] = sec ? _frvfdpic_osec_to_segment (output_bfd, sec->output_section) : (unsigned)-1; break; } if (check_segment[0] != check_segment[1] && IS_FDPIC (output_bfd)) { /* If you take this out, remove the #error from fdpic-static-6.d in the ld testsuite. */ /* This helps catch problems in GCC while we can't do more than static linking. The idea is to test whether the input file basename is crt0.o only once. */ if (silence_segment_error == 1) silence_segment_error = (strlen (input_bfd->filename) == 6 && strcmp (input_bfd->filename, "crt0.o") == 0) || (strlen (input_bfd->filename) > 6 && strcmp (input_bfd->filename + strlen (input_bfd->filename) - 7, "/crt0.o") == 0) ? -1 : 0; if (!silence_segment_error /* We don't want duplicate errors for undefined symbols. */ && !(picrel && picrel->symndx == -1 && picrel->d.h->root.type == bfd_link_hash_undefined)) { if (info->shared || info->pie) (*_bfd_error_handler) (_("%B(%A+0x%lx): reloc against `%s': %s"), input_bfd, input_section, (long)rel->r_offset, name, _("relocation references a different segment")); else info->callbacks->warning (info, _("relocation references a different segment"), name, input_bfd, input_section, rel->r_offset); } if (!silence_segment_error && (info->shared || info->pie)) return FALSE; elf_elfheader (output_bfd)->e_flags |= EF_FRV_PIC; } switch (r_type) { case R_FRV_GOTOFFHI: case R_FRV_TLSMOFFHI: /* We need the addend to be applied before we shift the value right. */ relocation += rel->r_addend; /* Fall through. */ case R_FRV_GOTHI: case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSDESCHI: relocation >>= 16; /* Fall through. */ case R_FRV_GOTLO: case R_FRV_FUNCDESC_GOTLO: case R_FRV_GOTOFFLO: case R_FRV_FUNCDESC_GOTOFFLO: case R_FRV_GOTTLSOFFLO: case R_FRV_GOTTLSDESCLO: case R_FRV_TLSMOFFLO: relocation &= 0xffff; break; default: break; } switch (r_type) { case R_FRV_LABEL24: if (! IS_FDPIC (output_bfd) || ! picrel->plt) break; /* Fall through. */ /* When referencing a GOT entry, a function descriptor or a PLT, we don't want the addend to apply to the reference, but rather to the referenced symbol. The actual entry will have already been created taking the addend into account, so cancel it out here. */ case R_FRV_GOT12: case R_FRV_GOTHI: case R_FRV_GOTLO: case R_FRV_FUNCDESC_GOT12: case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTLO: case R_FRV_FUNCDESC_GOTOFF12: case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_FUNCDESC_GOTOFFLO: case R_FRV_GETTLSOFF: case R_FRV_GOTTLSDESC12: case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: case R_FRV_GOTTLSOFF12: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: /* Note that we only want GOTOFFHI, not GOTOFFLO or GOTOFF12 here, since we do want to apply the addend to the others. Note that we've applied the addend to GOTOFFHI before we shifted it right. */ case R_FRV_GOTOFFHI: case R_FRV_TLSMOFFHI: relocation -= rel->r_addend; break; default: break; } if (r_type == R_FRV_HI16) r = elf32_frv_relocate_hi16 (input_bfd, rel, contents, relocation); else if (r_type == R_FRV_LO16) r = elf32_frv_relocate_lo16 (input_bfd, rel, contents, relocation); else if (r_type == R_FRV_LABEL24 || r_type == R_FRV_GETTLSOFF) r = elf32_frv_relocate_label24 (input_bfd, input_section, rel, contents, relocation); else if (r_type == R_FRV_GPREL12) r = elf32_frv_relocate_gprel12 (info, input_bfd, input_section, rel, contents, relocation); else if (r_type == R_FRV_GPRELU12) r = elf32_frv_relocate_gprelu12 (info, input_bfd, input_section, rel, contents, relocation); else if (r_type == R_FRV_GPRELLO) r = elf32_frv_relocate_gprello (info, input_bfd, input_section, rel, contents, relocation); else if (r_type == R_FRV_GPRELHI) r = elf32_frv_relocate_gprelhi (info, input_bfd, input_section, rel, contents, relocation); else if (r_type == R_FRV_TLSOFF || r_type == R_FRV_TLSDESC_VALUE) r = bfd_reloc_notsupported; else r = frv_final_link_relocate (howto, input_bfd, input_section, contents, rel, relocation); if (r != bfd_reloc_ok) { const char * msg = (const char *) NULL; switch (r) { case bfd_reloc_overflow: r = info->callbacks->reloc_overflow (info, (h ? &h->root : NULL), name, howto->name, (bfd_vma) 0, input_bfd, input_section, rel->r_offset); break; case bfd_reloc_undefined: r = info->callbacks->undefined_symbol (info, name, input_bfd, input_section, rel->r_offset, TRUE); break; case bfd_reloc_outofrange: msg = _("internal error: out of range error"); break; case bfd_reloc_notsupported: msg = _("internal error: unsupported relocation error"); break; case bfd_reloc_dangerous: msg = _("internal error: dangerous relocation"); break; default: msg = _("internal error: unknown error"); break; } if (msg) { (*_bfd_error_handler) (_("%B(%A+0x%lx): reloc against `%s': %s"), input_bfd, input_section, (long)rel->r_offset, name, msg); return FALSE; } if (! r) return FALSE; } } return TRUE; } /* Return the section that should be marked against GC for a given relocation. */ static asection * elf32_frv_gc_mark_hook (asection *sec, struct bfd_link_info *info, Elf_Internal_Rela *rel, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { if (h != NULL) switch (ELF32_R_TYPE (rel->r_info)) { case R_FRV_GNU_VTINHERIT: case R_FRV_GNU_VTENTRY: return NULL; } return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym); } /* Hook called by the linker routine which adds symbols from an object file. We use it to put .comm items in .scomm, and not .comm. */ static bfd_boolean elf32_frv_add_symbol_hook (abfd, info, sym, namep, flagsp, secp, valp) bfd *abfd; struct bfd_link_info *info; Elf_Internal_Sym *sym; const char **namep ATTRIBUTE_UNUSED; flagword *flagsp ATTRIBUTE_UNUSED; asection **secp; bfd_vma *valp; { if (sym->st_shndx == SHN_COMMON && !info->relocatable && (int)sym->st_size <= (int)bfd_get_gp_size (abfd)) { /* Common symbols less than or equal to -G nn bytes are automatically put into .sbss. */ asection *scomm = bfd_get_section_by_name (abfd, ".scommon"); if (scomm == NULL) { scomm = bfd_make_section_with_flags (abfd, ".scommon", (SEC_ALLOC | SEC_IS_COMMON | SEC_LINKER_CREATED)); if (scomm == NULL) return FALSE; } *secp = scomm; *valp = sym->st_size; } return TRUE; } /* We need dynamic symbols for every section, since segments can relocate independently. */ static bfd_boolean _frvfdpic_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED, struct bfd_link_info *info ATTRIBUTE_UNUSED, asection *p ATTRIBUTE_UNUSED) { switch (elf_section_data (p)->this_hdr.sh_type) { case SHT_PROGBITS: case SHT_NOBITS: /* If sh_type is yet undecided, assume it could be SHT_PROGBITS/SHT_NOBITS. */ case SHT_NULL: return FALSE; /* There shouldn't be section relative relocations against any other section. */ default: return TRUE; } } /* Create a .got section, as well as its additional info field. This is almost entirely copied from elflink.c:_bfd_elf_create_got_section(). */ static bfd_boolean _frv_create_got_section (bfd *abfd, struct bfd_link_info *info) { flagword flags, pltflags; asection *s; struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; const struct elf_backend_data *bed = get_elf_backend_data (abfd); int ptralign; int offset; /* This function may be called more than once. */ s = bfd_get_section_by_name (abfd, ".got"); if (s != NULL && (s->flags & SEC_LINKER_CREATED) != 0) return TRUE; /* Machine specific: although pointers are 32-bits wide, we want the GOT to be aligned to a 64-bit boundary, such that function descriptors in it can be accessed with 64-bit loads and stores. */ ptralign = 3; flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED); pltflags = flags; s = bfd_make_section_with_flags (abfd, ".got", flags); if (s == NULL || !bfd_set_section_alignment (abfd, s, ptralign)) return FALSE; if (bed->want_got_plt) { s = bfd_make_section_with_flags (abfd, ".got.plt", flags); if (s == NULL || !bfd_set_section_alignment (abfd, s, ptralign)) return FALSE; } if (bed->want_got_sym) { /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got (or .got.plt) section. We don't do this in the linker script because we don't want to define the symbol if we are not creating a global offset table. */ h = _bfd_elf_define_linkage_sym (abfd, info, s, "_GLOBAL_OFFSET_TABLE_"); elf_hash_table (info)->hgot = h; if (h == NULL) return FALSE; /* Machine-specific: we want the symbol for executables as well. */ if (! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } /* The first bit of the global offset table is the header. */ s->size += bed->got_header_size; /* This is the machine-specific part. Create and initialize section data for the got. */ if (IS_FDPIC (abfd)) { frvfdpic_got_section (info) = s; frvfdpic_relocs_info (info) = htab_try_create (1, frvfdpic_relocs_info_hash, frvfdpic_relocs_info_eq, (htab_del) NULL); if (! frvfdpic_relocs_info (info)) return FALSE; s = bfd_make_section_with_flags (abfd, ".rel.got", (flags | SEC_READONLY)); if (s == NULL || ! bfd_set_section_alignment (abfd, s, 2)) return FALSE; frvfdpic_gotrel_section (info) = s; /* Machine-specific. */ s = bfd_make_section_with_flags (abfd, ".rofixup", (flags | SEC_READONLY)); if (s == NULL || ! bfd_set_section_alignment (abfd, s, 2)) return FALSE; frvfdpic_gotfixup_section (info) = s; offset = -2048; flags = BSF_GLOBAL; } else { offset = 2048; flags = BSF_GLOBAL | BSF_WEAK; } /* Define _gp in .rofixup, for FDPIC, or .got otherwise. If it turns out that we're linking with a different linker script, the linker script will override it. */ bh = NULL; if (!(_bfd_generic_link_add_one_symbol (info, abfd, "_gp", flags, s, offset, (const char *) NULL, FALSE, bed->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->def_regular = 1; h->type = STT_OBJECT; /* h->other = STV_HIDDEN; */ /* Should we? */ /* Machine-specific: we want the symbol for executables as well. */ if (IS_FDPIC (abfd) && ! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; if (!IS_FDPIC (abfd)) return TRUE; /* FDPIC supports Thread Local Storage, and this may require a procedure linkage table for TLS PLT entries. */ /* This is mostly copied from elflink.c:_bfd_elf_create_dynamic_sections(). */ flags = pltflags; pltflags |= SEC_CODE; if (bed->plt_not_loaded) pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS); if (bed->plt_readonly) pltflags |= SEC_READONLY; s = bfd_make_section_with_flags (abfd, ".plt", pltflags); if (s == NULL || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment)) return FALSE; /* FRV-specific: remember it. */ frvfdpic_plt_section (info) = s; /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the .plt section. */ if (bed->want_plt_sym) { h = _bfd_elf_define_linkage_sym (abfd, info, s, "_PROCEDURE_LINKAGE_TABLE_"); elf_hash_table (info)->hplt = h; if (h == NULL) return FALSE; } /* FRV-specific: we want rel relocations for the plt. */ s = bfd_make_section_with_flags (abfd, ".rel.plt", flags | SEC_READONLY); if (s == NULL || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align)) return FALSE; /* FRV-specific: remember it. */ frvfdpic_pltrel_section (info) = s; return TRUE; } /* Make sure the got and plt sections exist, and that our pointers in the link hash table point to them. */ static bfd_boolean elf32_frvfdpic_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info) { /* This is mostly copied from elflink.c:_bfd_elf_create_dynamic_sections(). */ flagword flags; asection *s; const struct elf_backend_data *bed = get_elf_backend_data (abfd); flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED); /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and .rel[a].bss sections. */ /* FRV-specific: we want to create the GOT and the PLT in the FRV way. */ if (! _frv_create_got_section (abfd, info)) return FALSE; /* FRV-specific: make sure we created everything we wanted. */ BFD_ASSERT (frvfdpic_got_section (info) && frvfdpic_gotrel_section (info) && frvfdpic_gotfixup_section (info) && frvfdpic_plt_section (info) && frvfdpic_pltrel_section (info)); if (bed->want_dynbss) { /* The .dynbss section is a place to put symbols which are defined by dynamic objects, are referenced by regular objects, and are not functions. We must allocate space for them in the process image and use a R_*_COPY reloc to tell the dynamic linker to initialize them at run time. The linker script puts the .dynbss section into the .bss section of the final image. */ s = bfd_make_section_with_flags (abfd, ".dynbss", SEC_ALLOC | SEC_LINKER_CREATED); if (s == NULL) return FALSE; /* The .rel[a].bss section holds copy relocs. This section is not normally needed. We need to create it here, though, so that the linker will map it to an output section. We can't just create it only if we need it, because we will not know whether we need it until we have seen all the input files, and the first time the main linker code calls BFD after examining all the input files (size_dynamic_sections) the input sections have already been mapped to the output sections. If the section turns out not to be needed, we can discard it later. We will never need this section when generating a shared object, since they do not use copy relocs. */ if (! info->shared) { s = bfd_make_section_with_flags (abfd, (bed->default_use_rela_p ? ".rela.bss" : ".rel.bss"), flags | SEC_READONLY); if (s == NULL || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align)) return FALSE; } } return TRUE; } /* Compute the total GOT and PLT size required by each symbol in each range. Symbols may require up to 4 words in the GOT: an entry pointing to the symbol, an entry pointing to its function descriptor, and a private function descriptors taking two words. */ static void _frvfdpic_count_nontls_entries (struct frvfdpic_relocs_info *entry, struct _frvfdpic_dynamic_got_info *dinfo) { /* Allocate space for a GOT entry pointing to the symbol. */ if (entry->got12) dinfo->got12 += 4; else if (entry->gotlos) dinfo->gotlos += 4; else if (entry->gothilo) dinfo->gothilo += 4; else entry->relocs32--; entry->relocs32++; /* Allocate space for a GOT entry pointing to the function descriptor. */ if (entry->fdgot12) dinfo->got12 += 4; else if (entry->fdgotlos) dinfo->gotlos += 4; else if (entry->fdgothilo) dinfo->gothilo += 4; else entry->relocsfd--; entry->relocsfd++; /* Decide whether we need a PLT entry, a function descriptor in the GOT, and a lazy PLT entry for this symbol. */ entry->plt = entry->call && entry->symndx == -1 && ! FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h) && elf_hash_table (dinfo->info)->dynamic_sections_created; entry->privfd = entry->plt || entry->fdgoff12 || entry->fdgofflos || entry->fdgoffhilo || ((entry->fd || entry->fdgot12 || entry->fdgotlos || entry->fdgothilo) && (entry->symndx != -1 || FRVFDPIC_FUNCDESC_LOCAL (dinfo->info, entry->d.h))); entry->lazyplt = entry->privfd && entry->symndx == -1 && ! FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h) && ! (dinfo->info->flags & DF_BIND_NOW) && elf_hash_table (dinfo->info)->dynamic_sections_created; /* Allocate space for a function descriptor. */ if (entry->fdgoff12) dinfo->fd12 += 8; else if (entry->fdgofflos) dinfo->fdlos += 8; else if (entry->privfd && entry->plt) dinfo->fdplt += 8; else if (entry->privfd) dinfo->fdhilo += 8; else entry->relocsfdv--; entry->relocsfdv++; if (entry->lazyplt) dinfo->lzplt += 8; } /* Compute the total GOT size required by each TLS symbol in each range. Symbols may require up to 5 words in the GOT: an entry holding the TLS offset for the symbol, and an entry with a full TLS descriptor taking 4 words. */ static void _frvfdpic_count_tls_entries (struct frvfdpic_relocs_info *entry, struct _frvfdpic_dynamic_got_info *dinfo, bfd_boolean subtract) { const int l = subtract ? -1 : 1; /* Allocate space for a GOT entry with the TLS offset of the symbol. */ if (entry->tlsoff12) dinfo->got12 += 4 * l; else if (entry->tlsofflos) dinfo->gotlos += 4 * l; else if (entry->tlsoffhilo) dinfo->gothilo += 4 * l; else entry->relocstlsoff -= l; entry->relocstlsoff += l; /* If there's any TLSOFF relocation, mark the output file as not suitable for dlopening. This mark will remain even if we relax all such relocations, but this is not a problem, since we'll only do so for executables, and we definitely don't want anyone dlopening executables. */ if (entry->relocstlsoff) dinfo->info->flags |= DF_STATIC_TLS; /* Allocate space for a TLS descriptor. */ if (entry->tlsdesc12) dinfo->tlsd12 += 8 * l; else if (entry->tlsdesclos) dinfo->tlsdlos += 8 * l; else if (entry->tlsplt) dinfo->tlsdplt += 8 * l; else if (entry->tlsdeschilo) dinfo->tlsdhilo += 8 * l; else entry->relocstlsd -= l; entry->relocstlsd += l; } /* Compute the number of dynamic relocations and fixups that a symbol requires, and add (or subtract) from the grand and per-symbol totals. */ static void _frvfdpic_count_relocs_fixups (struct frvfdpic_relocs_info *entry, struct _frvfdpic_dynamic_got_info *dinfo, bfd_boolean subtract) { bfd_vma relocs = 0, fixups = 0, tlsrets = 0; if (!dinfo->info->executable || dinfo->info->pie) { relocs = entry->relocs32 + entry->relocsfd + entry->relocsfdv + entry->relocstlsd; /* In the executable, TLS relocations to symbols that bind locally (including those that resolve to global TLS offsets) are resolved immediately, without any need for fixups or dynamic relocations. In shared libraries, however, we must emit dynamic relocations even for local symbols, because we don't know the module id the library is going to get at run-time, nor its TLS base offset. */ if (!dinfo->info->executable || (entry->symndx == -1 && ! FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h))) relocs += entry->relocstlsoff; } else { if (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h)) { if (entry->symndx != -1 || entry->d.h->root.type != bfd_link_hash_undefweak) fixups += entry->relocs32 + 2 * entry->relocsfdv; fixups += entry->relocstlsd; tlsrets += entry->relocstlsd; } else { relocs += entry->relocs32 + entry->relocsfdv + entry->relocstlsoff + entry->relocstlsd; } if (entry->symndx != -1 || FRVFDPIC_FUNCDESC_LOCAL (dinfo->info, entry->d.h)) { if (entry->symndx != -1 || entry->d.h->root.type != bfd_link_hash_undefweak) fixups += entry->relocsfd; } else relocs += entry->relocsfd; } if (subtract) { relocs = - relocs; fixups = - fixups; tlsrets = - tlsrets; } entry->dynrelocs += relocs; entry->fixups += fixups; dinfo->relocs += relocs; dinfo->fixups += fixups; dinfo->tls_ret_refs += tlsrets; } /* Look for opportunities to relax TLS relocations. We can assume we're linking the main executable or a static-tls library, since otherwise we wouldn't have got here. When relaxing, we have to first undo any previous accounting of TLS uses of fixups, dynamic relocations, GOT and PLT entries. */ static void _frvfdpic_relax_tls_entries (struct frvfdpic_relocs_info *entry, struct _frvfdpic_dynamic_got_info *dinfo, bfd_boolean relaxing) { bfd_boolean changed = ! relaxing; BFD_ASSERT (dinfo->info->executable || (dinfo->info->flags & DF_STATIC_TLS)); if (entry->tlsdesc12 || entry->tlsdesclos || entry->tlsdeschilo) { if (! changed) { _frvfdpic_count_relocs_fixups (entry, dinfo, TRUE); _frvfdpic_count_tls_entries (entry, dinfo, TRUE); changed = TRUE; } /* When linking an executable, we can always decay GOTTLSDESC to TLSMOFF, if the symbol is local, or GOTTLSOFF, otherwise. When linking a static-tls shared library, using TLSMOFF is not an option, but we can still use GOTTLSOFF. When decaying to GOTTLSOFF, we must keep the GOT entry in range. We know it has to fit because we'll be trading the 4 words of hte TLS descriptor for a single word in the same range. */ if (! dinfo->info->executable || (entry->symndx == -1 && ! FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h))) { entry->tlsoff12 |= entry->tlsdesc12; entry->tlsofflos |= entry->tlsdesclos; entry->tlsoffhilo |= entry->tlsdeschilo; } entry->tlsdesc12 = entry->tlsdesclos = entry->tlsdeschilo = 0; } /* We can only decay TLSOFFs or call #gettlsoff to TLSMOFF in the main executable. We have to check whether the symbol's TLSOFF is in range for a setlos. For symbols with a hash entry, we can determine exactly what to do; for others locals, we don't have addresses handy, so we use the size of the TLS section as an approximation. If we get it wrong, we'll retain a GOT entry holding the TLS offset (without dynamic relocations or fixups), but we'll still optimize away the loads from it. Since TLS sizes are generally very small, it's probably not worth attempting to do better than this. */ if ((entry->tlsplt || entry->tlsoff12 || entry->tlsofflos || entry->tlsoffhilo) && dinfo->info->executable && relaxing && ((entry->symndx == -1 && FRVFDPIC_SYM_LOCAL (dinfo->info, entry->d.h) /* The above may hold for an undefweak TLS symbol, so make sure we don't have this case before accessing def.value and def.section. */ && (entry->d.h->root.type == bfd_link_hash_undefweak || (bfd_vma)(entry->d.h->root.u.def.value + (entry->d.h->root.u.def.section ->output_section->vma) + entry->d.h->root.u.def.section->output_offset + entry->addend - tls_biased_base (dinfo->info) + 32768) < (bfd_vma)65536)) || (entry->symndx != -1 && (elf_hash_table (dinfo->info)->tls_sec->size + abs (entry->addend) < 32768 + FRVFDPIC_TLS_BIAS)))) { if (! changed) { _frvfdpic_count_relocs_fixups (entry, dinfo, TRUE); _frvfdpic_count_tls_entries (entry, dinfo, TRUE); changed = TRUE; } entry->tlsplt = entry->tlsoff12 = entry->tlsofflos = entry->tlsoffhilo = 0; } /* We can decay `call #gettlsoff' to a ldi #tlsoff if we already have a #gottlsoff12 relocation for this entry, or if we can fit one more in the 12-bit (and 16-bit) ranges. */ if (entry->tlsplt && (entry->tlsoff12 || (relaxing && dinfo->got12 + dinfo->fd12 + dinfo->tlsd12 <= 4096 - 12 - 4 && (dinfo->got12 + dinfo->fd12 + dinfo->tlsd12 + dinfo->gotlos + dinfo->fdlos + dinfo->tlsdlos <= 65536 - 12 - 4)))) { if (! changed) { _frvfdpic_count_relocs_fixups (entry, dinfo, TRUE); _frvfdpic_count_tls_entries (entry, dinfo, TRUE); changed = TRUE; } entry->tlsoff12 = 1; entry->tlsplt = 0; } if (changed) { _frvfdpic_count_tls_entries (entry, dinfo, FALSE); _frvfdpic_count_relocs_fixups (entry, dinfo, FALSE); } return; } /* Compute the total GOT and PLT size required by each symbol in each range. * Symbols may require up to 4 words in the GOT: an entry pointing to the symbol, an entry pointing to its function descriptor, and a private function descriptors taking two words. */ static int _frvfdpic_count_got_plt_entries (void **entryp, void *dinfo_) { struct frvfdpic_relocs_info *entry = *entryp; struct _frvfdpic_dynamic_got_info *dinfo = dinfo_; _frvfdpic_count_nontls_entries (entry, dinfo); if (dinfo->info->executable || (dinfo->info->flags & DF_STATIC_TLS)) _frvfdpic_relax_tls_entries (entry, dinfo, FALSE); else { _frvfdpic_count_tls_entries (entry, dinfo, FALSE); _frvfdpic_count_relocs_fixups (entry, dinfo, FALSE); } return 1; } /* Determine the positive and negative ranges to be used by each offset range in the GOT. FDCUR and CUR, that must be aligned to a double-word boundary, are the minimum (negative) and maximum (positive) GOT offsets already used by previous ranges, except for an ODD entry that may have been left behind. GOT and FD indicate the size of GOT entries and function descriptors that must be placed within the range from -WRAP to WRAP. If there's room left, up to FDPLT bytes should be reserved for additional function descriptors. */ inline static bfd_signed_vma _frvfdpic_compute_got_alloc_data (struct _frvfdpic_dynamic_got_alloc_data *gad, bfd_signed_vma fdcur, bfd_signed_vma odd, bfd_signed_vma cur, bfd_vma got, bfd_vma fd, bfd_vma fdplt, bfd_vma tlsd, bfd_vma tlsdplt, bfd_vma wrap) { bfd_signed_vma wrapmin = -wrap; const bfd_vma tdescsz = 8; /* Start at the given initial points. */ gad->fdcur = fdcur; gad->cur = cur; /* If we had an incoming odd word and we have any got entries that are going to use it, consume it, otherwise leave gad->odd at zero. We might force gad->odd to zero and return the incoming odd such that it is used by the next range, but then GOT entries might appear to be out of order and we wouldn't be able to shorten the GOT by one word if it turns out to end with an unpaired GOT entry. */ if (odd && got) { gad->odd = odd; got -= 4; odd = 0; } else gad->odd = 0; /* If we're left with an unpaired GOT entry, compute its location such that we can return it. Otherwise, if got doesn't require an odd number of words here, either odd was already zero in the block above, or it was set to zero because got was non-zero, or got was already zero. In the latter case, we want the value of odd to carry over to the return statement, so we don't want to reset odd unless the condition below is true. */ if (got & 4) { odd = cur + got; got += 4; } /* Compute the tentative boundaries of this range. */ gad->max = cur + got; gad->min = fdcur - fd; gad->fdplt = 0; /* If function descriptors took too much space, wrap some of them around. */ if (gad->min < wrapmin) { gad->max += wrapmin - gad->min; gad->tmin = gad->min = wrapmin; } /* If GOT entries took too much space, wrap some of them around. This may well cause gad->min to become lower than wrapmin. This will cause a relocation overflow later on, so we don't have to report it here . */ if ((bfd_vma) gad->max > wrap) { gad->min -= gad->max - wrap; gad->max = wrap; } /* Add TLS descriptors. */ gad->tmax = gad->max + tlsd; gad->tmin = gad->min; gad->tlsdplt = 0; /* If TLS descriptors took too much space, wrap an integral number of them around. */ if ((bfd_vma) gad->tmax > wrap) { bfd_vma wrapsize = gad->tmax - wrap; wrapsize += tdescsz / 2; wrapsize &= ~ tdescsz / 2; gad->tmin -= wrapsize; gad->tmax -= wrapsize; } /* If there is space left and we have function descriptors referenced in PLT entries that could take advantage of shorter offsets, place them now. */ if (fdplt && gad->tmin > wrapmin) { bfd_vma fds; if ((bfd_vma) (gad->tmin - wrapmin) < fdplt) fds = gad->tmin - wrapmin; else fds = fdplt; fdplt -= fds; gad->min -= fds; gad->tmin -= fds; gad->fdplt += fds; } /* If there is more space left, try to place some more function descriptors for PLT entries. */ if (fdplt && (bfd_vma) gad->tmax < wrap) { bfd_vma fds; if ((bfd_vma) (wrap - gad->tmax) < fdplt) fds = wrap - gad->tmax; else fds = fdplt; fdplt -= fds; gad->max += fds; gad->tmax += fds; gad->fdplt += fds; } /* If there is space left and we have TLS descriptors referenced in PLT entries that could take advantage of shorter offsets, place them now. */ if (tlsdplt && gad->tmin > wrapmin) { bfd_vma tlsds; if ((bfd_vma) (gad->tmin - wrapmin) < tlsdplt) tlsds = (gad->tmin - wrapmin) & ~ (tdescsz / 2); else tlsds = tlsdplt; tlsdplt -= tlsds; gad->tmin -= tlsds; gad->tlsdplt += tlsds; } /* If there is more space left, try to place some more TLS descriptors for PLT entries. Although we could try to fit an additional TLS descriptor with half of it just before before the wrap point and another right past the wrap point, this might cause us to run out of space for the next region, so don't do it. */ if (tlsdplt && (bfd_vma) gad->tmax < wrap - tdescsz / 2) { bfd_vma tlsds; if ((bfd_vma) (wrap - gad->tmax) < tlsdplt) tlsds = (wrap - gad->tmax) & ~ (tdescsz / 2); else tlsds = tlsdplt; tlsdplt -= tlsds; gad->tmax += tlsds; gad->tlsdplt += tlsds; } /* If odd was initially computed as an offset past the wrap point, wrap it around. */ if (odd > gad->max) odd = gad->min + odd - gad->max; /* _frvfdpic_get_got_entry() below will always wrap gad->cur if needed before returning, so do it here too. This guarantees that, should cur and fdcur meet at the wrap point, they'll both be equal to min. */ if (gad->cur == gad->max) gad->cur = gad->min; /* Ditto for _frvfdpic_get_tlsdesc_entry(). */ gad->tcur = gad->max; if (gad->tcur == gad->tmax) gad->tcur = gad->tmin; return odd; } /* Compute the location of the next GOT entry, given the allocation data for a range. */ inline static bfd_signed_vma _frvfdpic_get_got_entry (struct _frvfdpic_dynamic_got_alloc_data *gad) { bfd_signed_vma ret; if (gad->odd) { /* If there was an odd word left behind, use it. */ ret = gad->odd; gad->odd = 0; } else { /* Otherwise, use the word pointed to by cur, reserve the next as an odd word, and skip to the next pair of words, possibly wrapping around. */ ret = gad->cur; gad->odd = gad->cur + 4; gad->cur += 8; if (gad->cur == gad->max) gad->cur = gad->min; } return ret; } /* Compute the location of the next function descriptor entry in the GOT, given the allocation data for a range. */ inline static bfd_signed_vma _frvfdpic_get_fd_entry (struct _frvfdpic_dynamic_got_alloc_data *gad) { /* If we're at the bottom, wrap around, and only then allocate the next pair of words. */ if (gad->fdcur == gad->min) gad->fdcur = gad->max; return gad->fdcur -= 8; } /* Compute the location of the next TLS descriptor entry in the GOT, given the allocation data for a range. */ inline static bfd_signed_vma _frvfdpic_get_tlsdesc_entry (struct _frvfdpic_dynamic_got_alloc_data *gad) { bfd_signed_vma ret; ret = gad->tcur; gad->tcur += 8; /* If we're at the top of the region, wrap around to the bottom. */ if (gad->tcur == gad->tmax) gad->tcur = gad->tmin; return ret; } /* Assign GOT offsets for every GOT entry and function descriptor. Doing everything in a single pass is tricky. */ static int _frvfdpic_assign_got_entries (void **entryp, void *info_) { struct frvfdpic_relocs_info *entry = *entryp; struct _frvfdpic_dynamic_got_plt_info *dinfo = info_; if (entry->got12) entry->got_entry = _frvfdpic_get_got_entry (&dinfo->got12); else if (entry->gotlos) entry->got_entry = _frvfdpic_get_got_entry (&dinfo->gotlos); else if (entry->gothilo) entry->got_entry = _frvfdpic_get_got_entry (&dinfo->gothilo); if (entry->fdgot12) entry->fdgot_entry = _frvfdpic_get_got_entry (&dinfo->got12); else if (entry->fdgotlos) entry->fdgot_entry = _frvfdpic_get_got_entry (&dinfo->gotlos); else if (entry->fdgothilo) entry->fdgot_entry = _frvfdpic_get_got_entry (&dinfo->gothilo); if (entry->fdgoff12) entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->got12); else if (entry->plt && dinfo->got12.fdplt) { dinfo->got12.fdplt -= 8; entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->got12); } else if (entry->fdgofflos) entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->gotlos); else if (entry->plt && dinfo->gotlos.fdplt) { dinfo->gotlos.fdplt -= 8; entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->gotlos); } else if (entry->plt) { dinfo->gothilo.fdplt -= 8; entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->gothilo); } else if (entry->privfd) entry->fd_entry = _frvfdpic_get_fd_entry (&dinfo->gothilo); if (entry->tlsoff12) entry->tlsoff_entry = _frvfdpic_get_got_entry (&dinfo->got12); else if (entry->tlsofflos) entry->tlsoff_entry = _frvfdpic_get_got_entry (&dinfo->gotlos); else if (entry->tlsoffhilo) entry->tlsoff_entry = _frvfdpic_get_got_entry (&dinfo->gothilo); if (entry->tlsdesc12) entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->got12); else if (entry->tlsplt && dinfo->got12.tlsdplt) { dinfo->got12.tlsdplt -= 8; entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->got12); } else if (entry->tlsdesclos) entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->gotlos); else if (entry->tlsplt && dinfo->gotlos.tlsdplt) { dinfo->gotlos.tlsdplt -= 8; entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->gotlos); } else if (entry->tlsplt) { dinfo->gothilo.tlsdplt -= 8; entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->gothilo); } else if (entry->tlsdeschilo) entry->tlsdesc_entry = _frvfdpic_get_tlsdesc_entry (&dinfo->gothilo); return 1; } /* Assign GOT offsets to private function descriptors used by PLT entries (or referenced by 32-bit offsets), as well as PLT entries and lazy PLT entries. */ static int _frvfdpic_assign_plt_entries (void **entryp, void *info_) { struct frvfdpic_relocs_info *entry = *entryp; struct _frvfdpic_dynamic_got_plt_info *dinfo = info_; if (entry->privfd) BFD_ASSERT (entry->fd_entry); if (entry->plt) { int size; /* We use the section's raw size to mark the location of the next PLT entry. */ entry->plt_entry = frvfdpic_plt_section (dinfo->g.info)->size; /* Figure out the length of this PLT entry based on the addressing mode we need to reach the function descriptor. */ BFD_ASSERT (entry->fd_entry); if (entry->fd_entry >= -(1 << (12 - 1)) && entry->fd_entry < (1 << (12 - 1))) size = 8; else if (entry->fd_entry >= -(1 << (16 - 1)) && entry->fd_entry < (1 << (16 - 1))) size = 12; else size = 16; frvfdpic_plt_section (dinfo->g.info)->size += size; } if (entry->lazyplt) { entry->lzplt_entry = dinfo->g.lzplt; dinfo->g.lzplt += 8; /* If this entry is the one that gets the resolver stub, account for the additional instruction. */ if (entry->lzplt_entry % FRVFDPIC_LZPLT_BLOCK_SIZE == FRVFDPIC_LZPLT_RESOLV_LOC) dinfo->g.lzplt += 4; } if (entry->tlsplt) { int size; entry->tlsplt_entry = frvfdpic_plt_section (dinfo->g.info)->size; if (dinfo->g.info->executable && (entry->symndx != -1 || FRVFDPIC_SYM_LOCAL (dinfo->g.info, entry->d.h))) { if ((bfd_signed_vma)entry->addend >= -(1 << (16 - 1)) /* FIXME: here we use the size of the TLS section as an upper bound for the value of the TLS symbol, because we may not know the exact value yet. If we get it wrong, we'll just waste a word in the PLT, and we should never get even close to 32 KiB of TLS anyway. */ && elf_hash_table (dinfo->g.info)->tls_sec && (elf_hash_table (dinfo->g.info)->tls_sec->size + (bfd_signed_vma)(entry->addend) <= (1 << (16 - 1)))) size = 8; else size = 12; } else if (entry->tlsoff_entry) { if (entry->tlsoff_entry >= -(1 << (12 - 1)) && entry->tlsoff_entry < (1 << (12 - 1))) size = 8; else if (entry->tlsoff_entry >= -(1 << (16 - 1)) && entry->tlsoff_entry < (1 << (16 - 1))) size = 12; else size = 16; } else { BFD_ASSERT (entry->tlsdesc_entry); if (entry->tlsdesc_entry >= -(1 << (12 - 1)) && entry->tlsdesc_entry < (1 << (12 - 1))) size = 8; else if (entry->tlsdesc_entry >= -(1 << (16 - 1)) && entry->tlsdesc_entry < (1 << (16 - 1))) size = 12; else size = 16; } frvfdpic_plt_section (dinfo->g.info)->size += size; } return 1; } /* Cancel out any effects of calling _frvfdpic_assign_got_entries and _frvfdpic_assign_plt_entries. */ static int _frvfdpic_reset_got_plt_entries (void **entryp, void *ignore ATTRIBUTE_UNUSED) { struct frvfdpic_relocs_info *entry = *entryp; entry->got_entry = 0; entry->fdgot_entry = 0; entry->fd_entry = 0; entry->plt_entry = (bfd_vma)-1; entry->lzplt_entry = (bfd_vma)-1; entry->tlsoff_entry = 0; entry->tlsdesc_entry = 0; entry->tlsplt_entry = (bfd_vma)-1; return 1; } /* Follow indirect and warning hash entries so that each got entry points to the final symbol definition. P must point to a pointer to the hash table we're traversing. Since this traversal may modify the hash table, we set this pointer to NULL to indicate we've made a potentially-destructive change to the hash table, so the traversal must be restarted. */ static int _frvfdpic_resolve_final_relocs_info (void **entryp, void *p) { struct frvfdpic_relocs_info *entry = *entryp; htab_t *htab = p; if (entry->symndx == -1) { struct elf_link_hash_entry *h = entry->d.h; struct frvfdpic_relocs_info *oentry; while (h->root.type == bfd_link_hash_indirect || h->root.type == bfd_link_hash_warning) h = (struct elf_link_hash_entry *)h->root.u.i.link; if (entry->d.h == h) return 1; oentry = frvfdpic_relocs_info_for_global (*htab, 0, h, entry->addend, NO_INSERT); if (oentry) { /* Merge the two entries. */ frvfdpic_pic_merge_early_relocs_info (oentry, entry); htab_clear_slot (*htab, entryp); return 1; } entry->d.h = h; /* If we can't find this entry with the new bfd hash, re-insert it, and get the traversal restarted. */ if (! htab_find (*htab, entry)) { htab_clear_slot (*htab, entryp); entryp = htab_find_slot (*htab, entry, INSERT); if (! *entryp) *entryp = entry; /* Abort the traversal, since the whole table may have moved, and leave it up to the parent to restart the process. */ *(htab_t *)p = NULL; return 0; } } return 1; } /* Compute the total size of the GOT, the PLT, the dynamic relocations section and the rofixup section. Assign locations for GOT and PLT entries. */ static bfd_boolean _frvfdpic_size_got_plt (bfd *output_bfd, struct _frvfdpic_dynamic_got_plt_info *gpinfop) { bfd_signed_vma odd; bfd_vma limit, tlslimit; struct bfd_link_info *info = gpinfop->g.info; bfd *dynobj = elf_hash_table (info)->dynobj; memcpy (frvfdpic_dynamic_got_plt_info (info), &gpinfop->g, sizeof (gpinfop->g)); odd = 12; /* Compute the total size taken by entries in the 12-bit and 16-bit ranges, to tell how many PLT function descriptors we can bring into the 12-bit range without causing the 16-bit range to overflow. */ limit = odd + gpinfop->g.got12 + gpinfop->g.gotlos + gpinfop->g.fd12 + gpinfop->g.fdlos + gpinfop->g.tlsd12 + gpinfop->g.tlsdlos; if (limit < (bfd_vma)1 << 16) limit = ((bfd_vma)1 << 16) - limit; else limit = 0; if (gpinfop->g.fdplt < limit) { tlslimit = (limit - gpinfop->g.fdplt) & ~ (bfd_vma) 8; limit = gpinfop->g.fdplt; } else tlslimit = 0; if (gpinfop->g.tlsdplt < tlslimit) tlslimit = gpinfop->g.tlsdplt; /* Determine the ranges of GOT offsets that we can use for each range of addressing modes. */ odd = _frvfdpic_compute_got_alloc_data (&gpinfop->got12, 0, odd, 16, gpinfop->g.got12, gpinfop->g.fd12, limit, gpinfop->g.tlsd12, tlslimit, (bfd_vma)1 << (12-1)); odd = _frvfdpic_compute_got_alloc_data (&gpinfop->gotlos, gpinfop->got12.tmin, odd, gpinfop->got12.tmax, gpinfop->g.gotlos, gpinfop->g.fdlos, gpinfop->g.fdplt - gpinfop->got12.fdplt, gpinfop->g.tlsdlos, gpinfop->g.tlsdplt - gpinfop->got12.tlsdplt, (bfd_vma)1 << (16-1)); odd = _frvfdpic_compute_got_alloc_data (&gpinfop->gothilo, gpinfop->gotlos.tmin, odd, gpinfop->gotlos.tmax, gpinfop->g.gothilo, gpinfop->g.fdhilo, gpinfop->g.fdplt - gpinfop->got12.fdplt - gpinfop->gotlos.fdplt, gpinfop->g.tlsdhilo, gpinfop->g.tlsdplt - gpinfop->got12.tlsdplt - gpinfop->gotlos.tlsdplt, (bfd_vma)1 << (32-1)); /* Now assign (most) GOT offsets. */ htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_assign_got_entries, gpinfop); frvfdpic_got_section (info)->size = gpinfop->gothilo.tmax - gpinfop->gothilo.tmin /* If an odd word is the last word of the GOT, we don't need this word to be part of the GOT. */ - (odd + 4 == gpinfop->gothilo.tmax ? 4 : 0); if (frvfdpic_got_section (info)->size == 0) frvfdpic_got_section (info)->flags |= SEC_EXCLUDE; else if (frvfdpic_got_section (info)->size == 12 && ! elf_hash_table (info)->dynamic_sections_created) { frvfdpic_got_section (info)->flags |= SEC_EXCLUDE; frvfdpic_got_section (info)->size = 0; } /* This will be non-NULL during relaxation. The assumption is that the size of one of these sections will never grow, only shrink, so we can use the larger buffer we allocated before. */ else if (frvfdpic_got_section (info)->contents == NULL) { frvfdpic_got_section (info)->contents = (bfd_byte *) bfd_zalloc (dynobj, frvfdpic_got_section (info)->size); if (frvfdpic_got_section (info)->contents == NULL) return FALSE; } if (frvfdpic_gotrel_section (info)) /* Subtract the number of lzplt entries, since those will generate relocations in the pltrel section. */ frvfdpic_gotrel_section (info)->size = (gpinfop->g.relocs - gpinfop->g.lzplt / 8) * get_elf_backend_data (output_bfd)->s->sizeof_rel; else BFD_ASSERT (gpinfop->g.relocs == 0); if (frvfdpic_gotrel_section (info)->size == 0) frvfdpic_gotrel_section (info)->flags |= SEC_EXCLUDE; else if (frvfdpic_gotrel_section (info)->contents == NULL) { frvfdpic_gotrel_section (info)->contents = (bfd_byte *) bfd_zalloc (dynobj, frvfdpic_gotrel_section (info)->size); if (frvfdpic_gotrel_section (info)->contents == NULL) return FALSE; } frvfdpic_gotfixup_section (info)->size = (gpinfop->g.fixups + 1) * 4; if (frvfdpic_gotfixup_section (info)->size == 0) frvfdpic_gotfixup_section (info)->flags |= SEC_EXCLUDE; else if (frvfdpic_gotfixup_section (info)->contents == NULL) { frvfdpic_gotfixup_section (info)->contents = (bfd_byte *) bfd_zalloc (dynobj, frvfdpic_gotfixup_section (info)->size); if (frvfdpic_gotfixup_section (info)->contents == NULL) return FALSE; } if (frvfdpic_pltrel_section (info)) { frvfdpic_pltrel_section (info)->size = gpinfop->g.lzplt / 8 * get_elf_backend_data (output_bfd)->s->sizeof_rel; if (frvfdpic_pltrel_section (info)->size == 0) frvfdpic_pltrel_section (info)->flags |= SEC_EXCLUDE; else if (frvfdpic_pltrel_section (info)->contents == NULL) { frvfdpic_pltrel_section (info)->contents = (bfd_byte *) bfd_zalloc (dynobj, frvfdpic_pltrel_section (info)->size); if (frvfdpic_pltrel_section (info)->contents == NULL) return FALSE; } } /* Add 4 bytes for every block of at most 65535 lazy PLT entries, such that there's room for the additional instruction needed to call the resolver. Since _frvfdpic_assign_got_entries didn't account for them, our block size is 4 bytes smaller than the real block size. */ if (frvfdpic_plt_section (info)) { frvfdpic_plt_section (info)->size = gpinfop->g.lzplt + ((gpinfop->g.lzplt + (FRVFDPIC_LZPLT_BLOCK_SIZE - 4) - 8) / (FRVFDPIC_LZPLT_BLOCK_SIZE - 4) * 4); } /* Reset it, such that _frvfdpic_assign_plt_entries() can use it to actually assign lazy PLT entries addresses. */ gpinfop->g.lzplt = 0; /* Save information that we're going to need to generate GOT and PLT entries. */ frvfdpic_got_initial_offset (info) = -gpinfop->gothilo.tmin; if (get_elf_backend_data (output_bfd)->want_got_sym) elf_hash_table (info)->hgot->root.u.def.value = frvfdpic_got_initial_offset (info); if (frvfdpic_plt_section (info)) frvfdpic_plt_initial_offset (info) = frvfdpic_plt_section (info)->size; /* Allocate a ret statement at plt_initial_offset, to be used by locally-resolved TLS descriptors. */ if (gpinfop->g.tls_ret_refs) frvfdpic_plt_section (info)->size += 4; htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_assign_plt_entries, gpinfop); /* Allocate the PLT section contents only after _frvfdpic_assign_plt_entries has a chance to add the size of the non-lazy PLT entries. */ if (frvfdpic_plt_section (info)) { if (frvfdpic_plt_section (info)->size == 0) frvfdpic_plt_section (info)->flags |= SEC_EXCLUDE; else if (frvfdpic_plt_section (info)->contents == NULL) { frvfdpic_plt_section (info)->contents = (bfd_byte *) bfd_zalloc (dynobj, frvfdpic_plt_section (info)->size); if (frvfdpic_plt_section (info)->contents == NULL) return FALSE; } } return TRUE; } /* Set the sizes of the dynamic sections. */ static bfd_boolean elf32_frvfdpic_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *s; struct _frvfdpic_dynamic_got_plt_info gpinfo; dynobj = elf_hash_table (info)->dynobj; BFD_ASSERT (dynobj != NULL); if (elf_hash_table (info)->dynamic_sections_created) { /* Set the contents of the .interp section to the interpreter. */ if (info->executable) { s = bfd_get_section_by_name (dynobj, ".interp"); BFD_ASSERT (s != NULL); s->size = sizeof ELF_DYNAMIC_INTERPRETER; s->contents = (bfd_byte *) ELF_DYNAMIC_INTERPRETER; } } memset (&gpinfo, 0, sizeof (gpinfo)); gpinfo.g.info = info; for (;;) { htab_t relocs = frvfdpic_relocs_info (info); htab_traverse (relocs, _frvfdpic_resolve_final_relocs_info, &relocs); if (relocs == frvfdpic_relocs_info (info)) break; } htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_count_got_plt_entries, &gpinfo.g); /* Allocate space to save the summary information, we're going to use it if we're doing relaxations. */ frvfdpic_dynamic_got_plt_info (info) = bfd_alloc (dynobj, sizeof (gpinfo.g)); if (!_frvfdpic_size_got_plt (output_bfd, &gpinfo)) return FALSE; if (elf_hash_table (info)->dynamic_sections_created) { if (frvfdpic_got_section (info)->size) if (!_bfd_elf_add_dynamic_entry (info, DT_PLTGOT, 0)) return FALSE; if (frvfdpic_pltrel_section (info)->size) if (!_bfd_elf_add_dynamic_entry (info, DT_PLTRELSZ, 0) || !_bfd_elf_add_dynamic_entry (info, DT_PLTREL, DT_REL) || !_bfd_elf_add_dynamic_entry (info, DT_JMPREL, 0)) return FALSE; if (frvfdpic_gotrel_section (info)->size) if (!_bfd_elf_add_dynamic_entry (info, DT_REL, 0) || !_bfd_elf_add_dynamic_entry (info, DT_RELSZ, 0) || !_bfd_elf_add_dynamic_entry (info, DT_RELENT, sizeof (Elf32_External_Rel))) return FALSE; } return TRUE; } static bfd_boolean elf32_frvfdpic_always_size_sections (bfd *output_bfd, struct bfd_link_info *info) { if (!info->relocatable) { struct elf_link_hash_entry *h; /* Force a PT_GNU_STACK segment to be created. */ if (! elf_tdata (output_bfd)->stack_flags) elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X; /* Define __stacksize if it's not defined yet. */ h = elf_link_hash_lookup (elf_hash_table (info), "__stacksize", FALSE, FALSE, FALSE); if (! h || h->root.type != bfd_link_hash_defined || h->type != STT_OBJECT || !h->def_regular) { struct bfd_link_hash_entry *bh = NULL; if (!(_bfd_generic_link_add_one_symbol (info, output_bfd, "__stacksize", BSF_GLOBAL, bfd_abs_section_ptr, DEFAULT_STACK_SIZE, (const char *) NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->def_regular = 1; h->type = STT_OBJECT; /* This one must NOT be hidden. */ } } return TRUE; } /* Check whether any of the relocations was optimized away, and subtract it from the relocation or fixup count. */ static bfd_boolean _frvfdpic_check_discarded_relocs (bfd *abfd, asection *sec, struct bfd_link_info *info, bfd_boolean *changed) { Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; Elf_Internal_Rela *rel, *erel; if ((sec->flags & SEC_RELOC) == 0 || sec->reloc_count == 0) return TRUE; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); rel = elf_section_data (sec)->relocs; /* Now examine each relocation. */ for (erel = rel + sec->reloc_count; rel < erel; rel++) { struct elf_link_hash_entry *h; unsigned long r_symndx; struct frvfdpic_relocs_info *picrel; struct _frvfdpic_dynamic_got_info *dinfo; if (ELF32_R_TYPE (rel->r_info) != R_FRV_32 && ELF32_R_TYPE (rel->r_info) != R_FRV_FUNCDESC) continue; if (_bfd_elf_section_offset (sec->output_section->owner, info, sec, rel->r_offset) != (bfd_vma)-1) continue; r_symndx = ELF32_R_SYM (rel->r_info); if (r_symndx < symtab_hdr->sh_info) h = NULL; else { h = sym_hashes[r_symndx - symtab_hdr->sh_info]; while (h->root.type == bfd_link_hash_indirect || h->root.type == bfd_link_hash_warning) h = (struct elf_link_hash_entry *)h->root.u.i.link; } if (h != NULL) picrel = frvfdpic_relocs_info_for_global (frvfdpic_relocs_info (info), abfd, h, rel->r_addend, NO_INSERT); else picrel = frvfdpic_relocs_info_for_local (frvfdpic_relocs_info (info), abfd, r_symndx, rel->r_addend, NO_INSERT); if (! picrel) return FALSE; *changed = TRUE; dinfo = frvfdpic_dynamic_got_plt_info (info); _frvfdpic_count_relocs_fixups (picrel, dinfo, TRUE); if (ELF32_R_TYPE (rel->r_info) == R_FRV_32) picrel->relocs32--; else /* we know (ELF32_R_TYPE (rel->r_info) == R_FRV_FUNCDESC) */ picrel->relocsfd--; _frvfdpic_count_relocs_fixups (picrel, dinfo, FALSE); } return TRUE; } static bfd_boolean frvfdpic_elf_discard_info (bfd *ibfd, struct elf_reloc_cookie *cookie ATTRIBUTE_UNUSED, struct bfd_link_info *info) { bfd_boolean changed = FALSE; asection *s; bfd *obfd = NULL; /* Account for relaxation of .eh_frame section. */ for (s = ibfd->sections; s; s = s->next) if (s->sec_info_type == ELF_INFO_TYPE_EH_FRAME) { if (!_frvfdpic_check_discarded_relocs (ibfd, s, info, &changed)) return FALSE; obfd = s->output_section->owner; } if (changed) { struct _frvfdpic_dynamic_got_plt_info gpinfo; memset (&gpinfo, 0, sizeof (gpinfo)); memcpy (&gpinfo.g, frvfdpic_dynamic_got_plt_info (info), sizeof (gpinfo.g)); /* Clear GOT and PLT assignments. */ htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_reset_got_plt_entries, NULL); if (!_frvfdpic_size_got_plt (obfd, &gpinfo)) return FALSE; } return TRUE; } /* Look for opportunities to relax TLS relocations. We can assume we're linking the main executable or a static-tls library, since otherwise we wouldn't have got here. */ static int _frvfdpic_relax_got_plt_entries (void **entryp, void *dinfo_) { struct frvfdpic_relocs_info *entry = *entryp; struct _frvfdpic_dynamic_got_info *dinfo = dinfo_; _frvfdpic_relax_tls_entries (entry, dinfo, TRUE); return 1; } static bfd_boolean elf32_frvfdpic_relax_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, struct bfd_link_info *info, bfd_boolean *again) { struct _frvfdpic_dynamic_got_plt_info gpinfo; if (info->relocatable) (*info->callbacks->einfo) (_("%P%F: --relax and -r may not be used together\n")); /* If we return early, we didn't change anything. */ *again = FALSE; /* We'll do our thing when requested to relax the GOT section. */ if (sec != frvfdpic_got_section (info)) return TRUE; /* We can only relax when linking the main executable or a library that can't be dlopened. */ if (! info->executable && ! (info->flags & DF_STATIC_TLS)) return TRUE; /* If there isn't a TLS section for this binary, we can't do anything about its TLS relocations (it probably doesn't have any. */ if (elf_hash_table (info)->tls_sec == NULL) return TRUE; memset (&gpinfo, 0, sizeof (gpinfo)); memcpy (&gpinfo.g, frvfdpic_dynamic_got_plt_info (info), sizeof (gpinfo.g)); /* Now look for opportunities to relax, adjusting the GOT usage as needed. */ htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_relax_got_plt_entries, &gpinfo.g); /* If we changed anything, reset and re-assign GOT and PLT entries. */ if (memcmp (frvfdpic_dynamic_got_plt_info (info), &gpinfo.g, sizeof (gpinfo.g)) != 0) { /* Clear GOT and PLT assignments. */ htab_traverse (frvfdpic_relocs_info (info), _frvfdpic_reset_got_plt_entries, NULL); /* The owner of the TLS section is the output bfd. There should be a better way to get to it. */ if (!_frvfdpic_size_got_plt (elf_hash_table (info)->tls_sec->owner, &gpinfo)) return FALSE; /* Repeat until we don't make any further changes. We could fail to introduce changes in a round if, for example, the 12-bit range is full, but we later release some space by getting rid of TLS descriptors in it. We have to repeat the whole process because we might have changed the size of a section processed before this one. */ *again = TRUE; } return TRUE; } static bfd_boolean elf32_frvfdpic_modify_program_headers (bfd *output_bfd, struct bfd_link_info *info) { struct elf_obj_tdata *tdata = elf_tdata (output_bfd); struct elf_segment_map *m; Elf_Internal_Phdr *p; /* objcopy and strip preserve what's already there using elf32_frvfdpic_copy_private_bfd_data (). */ if (! info) return TRUE; for (p = tdata->phdr, m = tdata->segment_map; m != NULL; m = m->next, p++) if (m->p_type == PT_GNU_STACK) break; if (m) { struct elf_link_hash_entry *h; /* Obtain the pointer to the __stacksize symbol. */ h = elf_link_hash_lookup (elf_hash_table (info), "__stacksize", FALSE, FALSE, FALSE); if (h) { while (h->root.type == bfd_link_hash_indirect || h->root.type == bfd_link_hash_warning) h = (struct elf_link_hash_entry *) h->root.u.i.link; BFD_ASSERT (h->root.type == bfd_link_hash_defined); } /* Set the header p_memsz from the symbol value. We intentionally ignore the symbol section. */ if (h && h->root.type == bfd_link_hash_defined) p->p_memsz = h->root.u.def.value; else p->p_memsz = DEFAULT_STACK_SIZE; p->p_align = 8; } return TRUE; } /* Fill in code and data in dynamic sections. */ static bfd_boolean elf32_frv_finish_dynamic_sections (bfd *output_bfd ATTRIBUTE_UNUSED, struct bfd_link_info *info ATTRIBUTE_UNUSED) { /* Nothing to be done for non-FDPIC. */ return TRUE; } static bfd_boolean elf32_frvfdpic_finish_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *sdyn; dynobj = elf_hash_table (info)->dynobj; if (frvfdpic_dynamic_got_plt_info (info)) { BFD_ASSERT (frvfdpic_dynamic_got_plt_info (info)->tls_ret_refs == 0); } if (frvfdpic_got_section (info)) { BFD_ASSERT (frvfdpic_gotrel_section (info)->size == (frvfdpic_gotrel_section (info)->reloc_count * sizeof (Elf32_External_Rel))); if (frvfdpic_gotfixup_section (info)) { struct elf_link_hash_entry *hgot = elf_hash_table (info)->hgot; bfd_vma got_value = hgot->root.u.def.value + hgot->root.u.def.section->output_section->vma + hgot->root.u.def.section->output_offset; struct bfd_link_hash_entry *hend; _frvfdpic_add_rofixup (output_bfd, frvfdpic_gotfixup_section (info), got_value, 0); if (frvfdpic_gotfixup_section (info)->size != (frvfdpic_gotfixup_section (info)->reloc_count * 4)) { error: (*_bfd_error_handler) ("LINKER BUG: .rofixup section size mismatch"); return FALSE; } hend = bfd_link_hash_lookup (info->hash, "__ROFIXUP_END__", FALSE, FALSE, TRUE); if (hend && (hend->type == bfd_link_hash_defined || hend->type == bfd_link_hash_defweak) && hend->u.def.section->output_section != NULL) { bfd_vma value = frvfdpic_gotfixup_section (info)->output_section->vma + frvfdpic_gotfixup_section (info)->output_offset + frvfdpic_gotfixup_section (info)->size - hend->u.def.section->output_section->vma - hend->u.def.section->output_offset; BFD_ASSERT (hend->u.def.value == value); if (hend->u.def.value != value) goto error; } } } if (frvfdpic_pltrel_section (info)) { BFD_ASSERT (frvfdpic_pltrel_section (info)->size == (frvfdpic_pltrel_section (info)->reloc_count * sizeof (Elf32_External_Rel))); } if (elf_hash_table (info)->dynamic_sections_created) { Elf32_External_Dyn * dyncon; Elf32_External_Dyn * dynconend; sdyn = bfd_get_section_by_name (dynobj, ".dynamic"); BFD_ASSERT (sdyn != NULL); dyncon = (Elf32_External_Dyn *) sdyn->contents; dynconend = (Elf32_External_Dyn *) (sdyn->contents + sdyn->size); for (; dyncon < dynconend; dyncon++) { Elf_Internal_Dyn dyn; bfd_elf32_swap_dyn_in (dynobj, dyncon, &dyn); switch (dyn.d_tag) { default: break; case DT_PLTGOT: dyn.d_un.d_ptr = frvfdpic_got_section (info)->output_section->vma + frvfdpic_got_section (info)->output_offset + frvfdpic_got_initial_offset (info); bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon); break; case DT_JMPREL: dyn.d_un.d_ptr = frvfdpic_pltrel_section (info) ->output_section->vma + frvfdpic_pltrel_section (info)->output_offset; bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon); break; case DT_PLTRELSZ: dyn.d_un.d_val = frvfdpic_pltrel_section (info)->size; bfd_elf32_swap_dyn_out (output_bfd, &dyn, dyncon); break; } } } return TRUE; } /* Adjust a symbol defined by a dynamic object and referenced by a regular object. */ static bfd_boolean elf32_frvfdpic_adjust_dynamic_symbol (struct bfd_link_info *info ATTRIBUTE_UNUSED, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED) { bfd * dynobj; dynobj = elf_hash_table (info)->dynobj; /* Make sure we know what is going on here. */ BFD_ASSERT (dynobj != NULL && (h->u.weakdef != NULL || (h->def_dynamic && h->ref_regular && !h->def_regular))); /* If this is a weak symbol, and there is a real definition, the processor independent code will have arranged for us to see the real definition first, and we can just use the same value. */ if (h->u.weakdef != NULL) { BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined || h->u.weakdef->root.type == bfd_link_hash_defweak); h->root.u.def.section = h->u.weakdef->root.u.def.section; h->root.u.def.value = h->u.weakdef->root.u.def.value; } return TRUE; } /* Perform any actions needed for dynamic symbols. */ static bfd_boolean elf32_frvfdpic_finish_dynamic_symbol (bfd *output_bfd ATTRIBUTE_UNUSED, struct bfd_link_info *info ATTRIBUTE_UNUSED, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym ATTRIBUTE_UNUSED) { return TRUE; } /* Decide whether to attempt to turn absptr or lsda encodings in shared libraries into pcrel within the given input section. */ static bfd_boolean frvfdpic_elf_use_relative_eh_frame (bfd *input_bfd ATTRIBUTE_UNUSED, struct bfd_link_info *info ATTRIBUTE_UNUSED, asection *eh_frame_section ATTRIBUTE_UNUSED) { /* We can't use PC-relative encodings in FDPIC binaries, in general. */ return FALSE; } /* Adjust the contents of an eh_frame_hdr section before they're output. */ static bfd_byte frvfdpic_elf_encode_eh_address (bfd *abfd, struct bfd_link_info *info, asection *osec, bfd_vma offset, asection *loc_sec, bfd_vma loc_offset, bfd_vma *encoded) { struct elf_link_hash_entry *h; h = elf_hash_table (info)->hgot; BFD_ASSERT (h && h->root.type == bfd_link_hash_defined); if (! h || (_frvfdpic_osec_to_segment (abfd, osec) == _frvfdpic_osec_to_segment (abfd, loc_sec->output_section))) return _bfd_elf_encode_eh_address (abfd, info, osec, offset, loc_sec, loc_offset, encoded); BFD_ASSERT (_frvfdpic_osec_to_segment (abfd, osec) == (_frvfdpic_osec_to_segment (abfd, h->root.u.def.section->output_section))); *encoded = osec->vma + offset - (h->root.u.def.value + h->root.u.def.section->output_section->vma + h->root.u.def.section->output_offset); return DW_EH_PE_datarel | DW_EH_PE_sdata4; } /* Look through the relocs for a section during the first phase. Besides handling virtual table relocs for gc, we have to deal with all sorts of PIC-related relocations. We describe below the general plan on how to handle such relocations, even though we only collect information at this point, storing them in hash tables for perusal of later passes. 32 relocations are propagated to the linker output when creating position-independent output. LO16 and HI16 relocations are not supposed to be encountered in this case. LABEL16 should always be resolvable by the linker, since it's only used by branches. LABEL24, on the other hand, is used by calls. If it turns out that the target of a call is a dynamic symbol, a PLT entry must be created for it, which triggers the creation of a private function descriptor and, unless lazy binding is disabled, a lazy PLT entry. GPREL relocations require the referenced symbol to be in the same segment as _gp, but this can only be checked later. All GOT, GOTOFF and FUNCDESC relocations require a .got section to exist. LABEL24 might as well, since it may require a PLT entry, that will require a got. Non-FUNCDESC GOT relocations require a GOT entry to be created regardless of whether the symbol is dynamic. However, since a global symbol that turns out to not be exported may have the same address of a non-dynamic symbol, we don't assign GOT entries at this point, such that we can share them in this case. A relocation for the GOT entry always has to be created, be it to offset a private symbol by the section load address, be it to get the symbol resolved dynamically. FUNCDESC GOT relocations require a GOT entry to be created, and handled as if a FUNCDESC relocation was applied to the GOT entry in an object file. FUNCDESC relocations referencing a symbol that turns out to NOT be dynamic cause a private function descriptor to be created. The FUNCDESC relocation then decays to a 32 relocation that points at the private descriptor. If the symbol is dynamic, the FUNCDESC relocation is propagated to the linker output, such that the dynamic linker creates the canonical descriptor, pointing to the dynamically-resolved definition of the function. Non-FUNCDESC GOTOFF relocations must always refer to non-dynamic symbols that are assigned to the same segment as the GOT, but we can only check this later, after we know the complete set of symbols defined and/or exported. FUNCDESC GOTOFF relocations require a function descriptor to be created and, unless lazy binding is disabled or the symbol is not dynamic, a lazy PLT entry. Since we can't tell at this point whether a symbol is going to be dynamic, we have to decide later whether to create a lazy PLT entry or bind the descriptor directly to the private function. FUNCDESC_VALUE relocations are not supposed to be present in object files, but they may very well be simply propagated to the linker output, since they have no side effect. A function descriptor always requires a FUNCDESC_VALUE relocation. Whether it's in .plt.rel or not depends on whether lazy binding is enabled and on whether the referenced symbol is dynamic. The existence of a lazy PLT requires the resolverStub lazy PLT entry to be present. As for assignment of GOT, PLT and lazy PLT entries, and private descriptors, we might do them all sequentially, but we can do better than that. For example, we can place GOT entries and private function descriptors referenced using 12-bit operands closer to the PIC register value, such that these relocations don't overflow. Those that are only referenced with LO16 relocations could come next, but we may as well place PLT-required function descriptors in the 12-bit range to make them shorter. Symbols referenced with LO16/HI16 may come next, but we may place additional function descriptors in the 16-bit range if we can reliably tell that we've already placed entries that are ever referenced with only LO16. PLT entries are therefore generated as small as possible, while not introducing relocation overflows in GOT or FUNCDESC_GOTOFF relocations. Lazy PLT entries could be generated before or after PLT entries, but not intermingled with them, such that we can have more lazy PLT entries in range for a branch to the resolverStub. The resolverStub should be emitted at the most distant location from the first lazy PLT entry such that it's still in range for a branch, or closer, if there isn't a need for so many lazy PLT entries. Additional lazy PLT entries may be emitted after the resolverStub, as long as branches are still in range. If the branch goes out of range, longer lazy PLT entries are emitted. We could further optimize PLT and lazy PLT entries by giving them priority in assignment to closer-to-gr17 locations depending on the number of occurrences of references to them (assuming a function that's called more often is more important for performance, so its PLT entry should be faster), or taking hints from the compiler. Given infinite time and money... :-) */ static bfd_boolean elf32_frv_check_relocs (abfd, info, sec, relocs) bfd *abfd; struct bfd_link_info *info; asection *sec; const Elf_Internal_Rela *relocs; { Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; const Elf_Internal_Rela *rel; const Elf_Internal_Rela *rel_end; bfd *dynobj; struct frvfdpic_relocs_info *picrel; if (info->relocatable) return TRUE; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); dynobj = elf_hash_table (info)->dynobj; rel_end = relocs + sec->reloc_count; for (rel = relocs; rel < rel_end; rel++) { struct elf_link_hash_entry *h; unsigned long r_symndx; r_symndx = ELF32_R_SYM (rel->r_info); if (r_symndx < symtab_hdr->sh_info) h = NULL; else { h = sym_hashes[r_symndx - symtab_hdr->sh_info]; while (h->root.type == bfd_link_hash_indirect || h->root.type == bfd_link_hash_warning) h = (struct elf_link_hash_entry *) h->root.u.i.link; } switch (ELF32_R_TYPE (rel->r_info)) { case R_FRV_GETTLSOFF: case R_FRV_TLSDESC_VALUE: case R_FRV_GOTTLSDESC12: case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: case R_FRV_GOTTLSOFF12: case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: case R_FRV_TLSOFF: case R_FRV_GOT12: case R_FRV_GOTHI: case R_FRV_GOTLO: case R_FRV_FUNCDESC_GOT12: case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTLO: case R_FRV_GOTOFF12: case R_FRV_GOTOFFHI: case R_FRV_GOTOFFLO: case R_FRV_FUNCDESC_GOTOFF12: case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_FUNCDESC_GOTOFFLO: case R_FRV_FUNCDESC: case R_FRV_FUNCDESC_VALUE: case R_FRV_TLSMOFF12: case R_FRV_TLSMOFFHI: case R_FRV_TLSMOFFLO: case R_FRV_TLSMOFF: if (! IS_FDPIC (abfd)) goto bad_reloc; /* Fall through. */ case R_FRV_GPREL12: case R_FRV_GPRELU12: case R_FRV_GPRELHI: case R_FRV_GPRELLO: case R_FRV_LABEL24: case R_FRV_32: if (! dynobj) { elf_hash_table (info)->dynobj = dynobj = abfd; if (! _frv_create_got_section (abfd, info)) return FALSE; } if (! IS_FDPIC (abfd)) { picrel = NULL; break; } if (h != NULL) { if (h->dynindx == -1) switch (ELF_ST_VISIBILITY (h->other)) { case STV_INTERNAL: case STV_HIDDEN: break; default: bfd_elf_link_record_dynamic_symbol (info, h); break; } picrel = frvfdpic_relocs_info_for_global (frvfdpic_relocs_info (info), abfd, h, rel->r_addend, INSERT); } else picrel = frvfdpic_relocs_info_for_local (frvfdpic_relocs_info (info), abfd, r_symndx, rel->r_addend, INSERT); if (! picrel) return FALSE; break; default: picrel = NULL; break; } switch (ELF32_R_TYPE (rel->r_info)) { case R_FRV_LABEL24: if (IS_FDPIC (abfd)) picrel->call = 1; break; case R_FRV_FUNCDESC_VALUE: picrel->relocsfdv++; if (bfd_get_section_flags (abfd, sec) & SEC_ALLOC) picrel->relocs32--; /* Fall through. */ case R_FRV_32: if (! IS_FDPIC (abfd)) break; picrel->sym = 1; if (bfd_get_section_flags (abfd, sec) & SEC_ALLOC) picrel->relocs32++; break; case R_FRV_GOT12: picrel->got12 = 1; break; case R_FRV_GOTHI: case R_FRV_GOTLO: picrel->gothilo = 1; break; case R_FRV_FUNCDESC_GOT12: picrel->fdgot12 = 1; break; case R_FRV_FUNCDESC_GOTHI: case R_FRV_FUNCDESC_GOTLO: picrel->fdgothilo = 1; break; case R_FRV_GOTOFF12: case R_FRV_GOTOFFHI: case R_FRV_GOTOFFLO: picrel->gotoff = 1; break; case R_FRV_FUNCDESC_GOTOFF12: picrel->fdgoff12 = 1; break; case R_FRV_FUNCDESC_GOTOFFHI: case R_FRV_FUNCDESC_GOTOFFLO: picrel->fdgoffhilo = 1; break; case R_FRV_FUNCDESC: picrel->fd = 1; picrel->relocsfd++; break; case R_FRV_GETTLSOFF: picrel->tlsplt = 1; break; case R_FRV_TLSDESC_VALUE: picrel->relocstlsd++; goto bad_reloc; case R_FRV_GOTTLSDESC12: picrel->tlsdesc12 = 1; break; case R_FRV_GOTTLSDESCHI: case R_FRV_GOTTLSDESCLO: picrel->tlsdeschilo = 1; break; case R_FRV_TLSMOFF12: case R_FRV_TLSMOFFHI: case R_FRV_TLSMOFFLO: case R_FRV_TLSMOFF: break; case R_FRV_GOTTLSOFF12: picrel->tlsoff12 = 1; info->flags |= DF_STATIC_TLS; break; case R_FRV_GOTTLSOFFHI: case R_FRV_GOTTLSOFFLO: picrel->tlsoffhilo = 1; info->flags |= DF_STATIC_TLS; break; case R_FRV_TLSOFF: picrel->relocstlsoff++; info->flags |= DF_STATIC_TLS; goto bad_reloc; /* This relocation describes the C++ object vtable hierarchy. Reconstruct it for later use during GC. */ case R_FRV_GNU_VTINHERIT: if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset)) return FALSE; break; /* This relocation describes which C++ vtable entries are actually used. Record for later use during GC. */ case R_FRV_GNU_VTENTRY: BFD_ASSERT (h != NULL); if (h != NULL && !bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_addend)) return FALSE; break; case R_FRV_LABEL16: case R_FRV_LO16: case R_FRV_HI16: case R_FRV_GPREL12: case R_FRV_GPRELU12: case R_FRV_GPREL32: case R_FRV_GPRELHI: case R_FRV_GPRELLO: case R_FRV_TLSDESC_RELAX: case R_FRV_GETTLSOFF_RELAX: case R_FRV_TLSOFF_RELAX: break; default: bad_reloc: (*_bfd_error_handler) (_("%B: unsupported relocation type %i"), abfd, ELF32_R_TYPE (rel->r_info)); return FALSE; } } return TRUE; } /* Return the machine subcode from the ELF e_flags header. */ static int elf32_frv_machine (abfd) bfd *abfd; { switch (elf_elfheader (abfd)->e_flags & EF_FRV_CPU_MASK) { default: break; case EF_FRV_CPU_FR550: return bfd_mach_fr550; case EF_FRV_CPU_FR500: return bfd_mach_fr500; case EF_FRV_CPU_FR450: return bfd_mach_fr450; case EF_FRV_CPU_FR405: return bfd_mach_fr400; case EF_FRV_CPU_FR400: return bfd_mach_fr400; case EF_FRV_CPU_FR300: return bfd_mach_fr300; case EF_FRV_CPU_SIMPLE: return bfd_mach_frvsimple; case EF_FRV_CPU_TOMCAT: return bfd_mach_frvtomcat; } return bfd_mach_frv; } /* Set the right machine number for a FRV ELF file. */ static bfd_boolean elf32_frv_object_p (abfd) bfd *abfd; { bfd_default_set_arch_mach (abfd, bfd_arch_frv, elf32_frv_machine (abfd)); return (((elf_elfheader (abfd)->e_flags & EF_FRV_FDPIC) != 0) == (IS_FDPIC (abfd))); } /* Function to set the ELF flag bits. */ static bfd_boolean frv_elf_set_private_flags (abfd, flags) bfd *abfd; flagword flags; { elf_elfheader (abfd)->e_flags = flags; elf_flags_init (abfd) = TRUE; return TRUE; } /* Copy backend specific data from one object module to another. */ static bfd_boolean frv_elf_copy_private_bfd_data (ibfd, obfd) bfd *ibfd; bfd *obfd; { if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour || bfd_get_flavour (obfd) != bfd_target_elf_flavour) return TRUE; BFD_ASSERT (!elf_flags_init (obfd) || elf_elfheader (obfd)->e_flags == elf_elfheader (ibfd)->e_flags); elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags; elf_flags_init (obfd) = TRUE; /* Copy object attributes. */ _bfd_elf_copy_obj_attributes (ibfd, obfd); return TRUE; } /* Return true if the architecture described by elf header flag EXTENSION is an extension of the architecture described by BASE. */ static bfd_boolean frv_elf_arch_extension_p (flagword base, flagword extension) { if (base == extension) return TRUE; /* CPU_GENERIC code can be merged with code for a specific architecture, in which case the result is marked as being for the specific architecture. Everything is therefore an extension of CPU_GENERIC. */ if (base == EF_FRV_CPU_GENERIC) return TRUE; if (extension == EF_FRV_CPU_FR450) if (base == EF_FRV_CPU_FR400 || base == EF_FRV_CPU_FR405) return TRUE; if (extension == EF_FRV_CPU_FR405) if (base == EF_FRV_CPU_FR400) return TRUE; return FALSE; } static bfd_boolean elf32_frvfdpic_copy_private_bfd_data (bfd *ibfd, bfd *obfd) { unsigned i; if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour || bfd_get_flavour (obfd) != bfd_target_elf_flavour) return TRUE; if (! frv_elf_copy_private_bfd_data (ibfd, obfd)) return FALSE; if (! elf_tdata (ibfd) || ! elf_tdata (ibfd)->phdr || ! elf_tdata (obfd) || ! elf_tdata (obfd)->phdr) return TRUE; /* Copy the stack size. */ for (i = 0; i < elf_elfheader (ibfd)->e_phnum; i++) if (elf_tdata (ibfd)->phdr[i].p_type == PT_GNU_STACK) { Elf_Internal_Phdr *iphdr = &elf_tdata (ibfd)->phdr[i]; for (i = 0; i < elf_elfheader (obfd)->e_phnum; i++) if (elf_tdata (obfd)->phdr[i].p_type == PT_GNU_STACK) { memcpy (&elf_tdata (obfd)->phdr[i], iphdr, sizeof (*iphdr)); /* Rewrite the phdrs, since we're only called after they were first written. */ if (bfd_seek (obfd, (bfd_signed_vma) get_elf_backend_data (obfd) ->s->sizeof_ehdr, SEEK_SET) != 0 || get_elf_backend_data (obfd)->s ->write_out_phdrs (obfd, elf_tdata (obfd)->phdr, elf_elfheader (obfd)->e_phnum) != 0) return FALSE; break; } break; } return TRUE; } /* Merge backend specific data from an object file to the output object file when linking. */ static bfd_boolean frv_elf_merge_private_bfd_data (ibfd, obfd) bfd *ibfd; bfd *obfd; { flagword old_flags, old_partial; flagword new_flags, new_partial; bfd_boolean error = FALSE; char new_opt[80]; char old_opt[80]; new_opt[0] = old_opt[0] = '\0'; new_flags = elf_elfheader (ibfd)->e_flags; old_flags = elf_elfheader (obfd)->e_flags; if (new_flags & EF_FRV_FDPIC) new_flags &= ~EF_FRV_PIC; #ifdef DEBUG (*_bfd_error_handler) ("old_flags = 0x%.8lx, new_flags = 0x%.8lx, init = %s, filename = %s", old_flags, new_flags, elf_flags_init (obfd) ? "yes" : "no", bfd_get_filename (ibfd)); #endif if (!elf_flags_init (obfd)) /* First call, no flags set. */ { elf_flags_init (obfd) = TRUE; old_flags = new_flags; } else if (new_flags == old_flags) /* Compatible flags are ok. */ ; else /* Possibly incompatible flags. */ { /* Warn if different # of gprs are used. Note, 0 means nothing is said about the size of gprs. */ new_partial = (new_flags & EF_FRV_GPR_MASK); old_partial = (old_flags & EF_FRV_GPR_MASK); if (new_partial == old_partial) ; else if (new_partial == 0) ; else if (old_partial == 0) old_flags |= new_partial; else { switch (new_partial) { default: strcat (new_opt, " -mgpr-??"); break; case EF_FRV_GPR_32: strcat (new_opt, " -mgpr-32"); break; case EF_FRV_GPR_64: strcat (new_opt, " -mgpr-64"); break; } switch (old_partial) { default: strcat (old_opt, " -mgpr-??"); break; case EF_FRV_GPR_32: strcat (old_opt, " -mgpr-32"); break; case EF_FRV_GPR_64: strcat (old_opt, " -mgpr-64"); break; } } /* Warn if different # of fprs are used. Note, 0 means nothing is said about the size of fprs. */ new_partial = (new_flags & EF_FRV_FPR_MASK); old_partial = (old_flags & EF_FRV_FPR_MASK); if (new_partial == old_partial) ; else if (new_partial == 0) ; else if (old_partial == 0) old_flags |= new_partial; else { switch (new_partial) { default: strcat (new_opt, " -mfpr-?"); break; case EF_FRV_FPR_32: strcat (new_opt, " -mfpr-32"); break; case EF_FRV_FPR_64: strcat (new_opt, " -mfpr-64"); break; case EF_FRV_FPR_NONE: strcat (new_opt, " -msoft-float"); break; } switch (old_partial) { default: strcat (old_opt, " -mfpr-?"); break; case EF_FRV_FPR_32: strcat (old_opt, " -mfpr-32"); break; case EF_FRV_FPR_64: strcat (old_opt, " -mfpr-64"); break; case EF_FRV_FPR_NONE: strcat (old_opt, " -msoft-float"); break; } } /* Warn if different dword support was used. Note, 0 means nothing is said about the dword support. */ new_partial = (new_flags & EF_FRV_DWORD_MASK); old_partial = (old_flags & EF_FRV_DWORD_MASK); if (new_partial == old_partial) ; else if (new_partial == 0) ; else if (old_partial == 0) old_flags |= new_partial; else { switch (new_partial) { default: strcat (new_opt, " -mdword-?"); break; case EF_FRV_DWORD_YES: strcat (new_opt, " -mdword"); break; case EF_FRV_DWORD_NO: strcat (new_opt, " -mno-dword"); break; } switch (old_partial) { default: strcat (old_opt, " -mdword-?"); break; case EF_FRV_DWORD_YES: strcat (old_opt, " -mdword"); break; case EF_FRV_DWORD_NO: strcat (old_opt, " -mno-dword"); break; } } /* Or in flags that accumulate (ie, if one module uses it, mark that the feature is used. */ old_flags |= new_flags & (EF_FRV_DOUBLE | EF_FRV_MEDIA | EF_FRV_MULADD | EF_FRV_NON_PIC_RELOCS); /* If any module was compiled without -G0, clear the G0 bit. */ old_flags = ((old_flags & ~ EF_FRV_G0) | (old_flags & new_flags & EF_FRV_G0)); /* If any module was compiled without -mnopack, clear the mnopack bit. */ old_flags = ((old_flags & ~ EF_FRV_NOPACK) | (old_flags & new_flags & EF_FRV_NOPACK)); /* We don't have to do anything if the pic flags are the same, or the new module(s) were compiled with -mlibrary-pic. */ new_partial = (new_flags & EF_FRV_PIC_FLAGS); old_partial = (old_flags & EF_FRV_PIC_FLAGS); if ((new_partial == old_partial) || ((new_partial & EF_FRV_LIBPIC) != 0)) ; /* If the old module(s) were compiled with -mlibrary-pic, copy in the pic flags if any from the new module. */ else if ((old_partial & EF_FRV_LIBPIC) != 0) old_flags = (old_flags & ~ EF_FRV_PIC_FLAGS) | new_partial; /* If we have mixtures of -fpic and -fPIC, or in both bits. */ else if (new_partial != 0 && old_partial != 0) old_flags |= new_partial; /* One module was compiled for pic and the other was not, see if we have had any relocations that are not pic-safe. */ else { if ((old_flags & EF_FRV_NON_PIC_RELOCS) == 0) old_flags |= new_partial; else { old_flags &= ~ EF_FRV_PIC_FLAGS; #ifndef FRV_NO_PIC_ERROR error = TRUE; (*_bfd_error_handler) (_("%s: compiled with %s and linked with modules that use non-pic relocations"), bfd_get_filename (ibfd), (new_flags & EF_FRV_BIGPIC) ? "-fPIC" : "-fpic"); #endif } } /* Warn if different cpu is used (allow a specific cpu to override the generic cpu). */ new_partial = (new_flags & EF_FRV_CPU_MASK); old_partial = (old_flags & EF_FRV_CPU_MASK); if (frv_elf_arch_extension_p (new_partial, old_partial)) ; else if (frv_elf_arch_extension_p (old_partial, new_partial)) old_flags = (old_flags & ~EF_FRV_CPU_MASK) | new_partial; else { switch (new_partial) { default: strcat (new_opt, " -mcpu=?"); break; case EF_FRV_CPU_GENERIC: strcat (new_opt, " -mcpu=frv"); break; case EF_FRV_CPU_SIMPLE: strcat (new_opt, " -mcpu=simple"); break; case EF_FRV_CPU_FR550: strcat (new_opt, " -mcpu=fr550"); break; case EF_FRV_CPU_FR500: strcat (new_opt, " -mcpu=fr500"); break; case EF_FRV_CPU_FR450: strcat (new_opt, " -mcpu=fr450"); break; case EF_FRV_CPU_FR405: strcat (new_opt, " -mcpu=fr405"); break; case EF_FRV_CPU_FR400: strcat (new_opt, " -mcpu=fr400"); break; case EF_FRV_CPU_FR300: strcat (new_opt, " -mcpu=fr300"); break; case EF_FRV_CPU_TOMCAT: strcat (new_opt, " -mcpu=tomcat"); break; } switch (old_partial) { default: strcat (old_opt, " -mcpu=?"); break; case EF_FRV_CPU_GENERIC: strcat (old_opt, " -mcpu=frv"); break; case EF_FRV_CPU_SIMPLE: strcat (old_opt, " -mcpu=simple"); break; case EF_FRV_CPU_FR550: strcat (old_opt, " -mcpu=fr550"); break; case EF_FRV_CPU_FR500: strcat (old_opt, " -mcpu=fr500"); break; case EF_FRV_CPU_FR450: strcat (old_opt, " -mcpu=fr450"); break; case EF_FRV_CPU_FR405: strcat (old_opt, " -mcpu=fr405"); break; case EF_FRV_CPU_FR400: strcat (old_opt, " -mcpu=fr400"); break; case EF_FRV_CPU_FR300: strcat (old_opt, " -mcpu=fr300"); break; case EF_FRV_CPU_TOMCAT: strcat (old_opt, " -mcpu=tomcat"); break; } } /* Print out any mismatches from above. */ if (new_opt[0]) { error = TRUE; (*_bfd_error_handler) (_("%s: compiled with %s and linked with modules compiled with %s"), bfd_get_filename (ibfd), new_opt, old_opt); } /* Warn about any other mismatches */ new_partial = (new_flags & ~ EF_FRV_ALL_FLAGS); old_partial = (old_flags & ~ EF_FRV_ALL_FLAGS); if (new_partial != old_partial) { old_flags |= new_partial; error = TRUE; (*_bfd_error_handler) (_("%s: uses different unknown e_flags (0x%lx) fields than previous modules (0x%lx)"), bfd_get_filename (ibfd), (long)new_partial, (long)old_partial); } } /* If the cpu is -mcpu=simple, then set the -mnopack bit. */ if ((old_flags & EF_FRV_CPU_MASK) == EF_FRV_CPU_SIMPLE) old_flags |= EF_FRV_NOPACK; /* Update the old flags now with changes made above. */ old_partial = elf_elfheader (obfd)->e_flags & EF_FRV_CPU_MASK; elf_elfheader (obfd)->e_flags = old_flags; if (old_partial != (old_flags & EF_FRV_CPU_MASK)) bfd_default_set_arch_mach (obfd, bfd_arch_frv, elf32_frv_machine (obfd)); if (((new_flags & EF_FRV_FDPIC) == 0) != (! IS_FDPIC (ibfd))) { error = TRUE; if (IS_FDPIC (obfd)) (*_bfd_error_handler) (_("%s: cannot link non-fdpic object file into fdpic executable"), bfd_get_filename (ibfd)); else (*_bfd_error_handler) (_("%s: cannot link fdpic object file into non-fdpic executable"), bfd_get_filename (ibfd)); } if (error) bfd_set_error (bfd_error_bad_value); return !error; } bfd_boolean frv_elf_print_private_bfd_data (abfd, ptr) bfd *abfd; PTR ptr; { FILE *file = (FILE *) ptr; flagword flags; BFD_ASSERT (abfd != NULL && ptr != NULL); /* Print normal ELF private data. */ _bfd_elf_print_private_bfd_data (abfd, ptr); flags = elf_elfheader (abfd)->e_flags; fprintf (file, _("private flags = 0x%lx:"), (unsigned long) flags); switch (flags & EF_FRV_CPU_MASK) { default: break; case EF_FRV_CPU_SIMPLE: fprintf (file, " -mcpu=simple"); break; case EF_FRV_CPU_FR550: fprintf (file, " -mcpu=fr550"); break; case EF_FRV_CPU_FR500: fprintf (file, " -mcpu=fr500"); break; case EF_FRV_CPU_FR450: fprintf (file, " -mcpu=fr450"); break; case EF_FRV_CPU_FR405: fprintf (file, " -mcpu=fr405"); break; case EF_FRV_CPU_FR400: fprintf (file, " -mcpu=fr400"); break; case EF_FRV_CPU_FR300: fprintf (file, " -mcpu=fr300"); break; case EF_FRV_CPU_TOMCAT: fprintf (file, " -mcpu=tomcat"); break; } switch (flags & EF_FRV_GPR_MASK) { default: break; case EF_FRV_GPR_32: fprintf (file, " -mgpr-32"); break; case EF_FRV_GPR_64: fprintf (file, " -mgpr-64"); break; } switch (flags & EF_FRV_FPR_MASK) { default: break; case EF_FRV_FPR_32: fprintf (file, " -mfpr-32"); break; case EF_FRV_FPR_64: fprintf (file, " -mfpr-64"); break; case EF_FRV_FPR_NONE: fprintf (file, " -msoft-float"); break; } switch (flags & EF_FRV_DWORD_MASK) { default: break; case EF_FRV_DWORD_YES: fprintf (file, " -mdword"); break; case EF_FRV_DWORD_NO: fprintf (file, " -mno-dword"); break; } if (flags & EF_FRV_DOUBLE) fprintf (file, " -mdouble"); if (flags & EF_FRV_MEDIA) fprintf (file, " -mmedia"); if (flags & EF_FRV_MULADD) fprintf (file, " -mmuladd"); if (flags & EF_FRV_PIC) fprintf (file, " -fpic"); if (flags & EF_FRV_BIGPIC) fprintf (file, " -fPIC"); if (flags & EF_FRV_LIBPIC) fprintf (file, " -mlibrary-pic"); if (flags & EF_FRV_FDPIC) fprintf (file, " -mfdpic"); if (flags & EF_FRV_NON_PIC_RELOCS) fprintf (file, " non-pic relocations"); if (flags & EF_FRV_G0) fprintf (file, " -G0"); fputc ('\n', file); return TRUE; } /* Support for core dump NOTE sections. */ static bfd_boolean elf32_frv_grok_prstatus (bfd *abfd, Elf_Internal_Note *note) { int offset; unsigned int raw_size; switch (note->descsz) { default: return FALSE; /* The Linux/FRV elf_prstatus struct is 268 bytes long. The other hardcoded offsets and sizes listed below (and contained within this lexical block) refer to fields in the target's elf_prstatus struct. */ case 268: /* `pr_cursig' is at offset 12. */ elf_tdata (abfd)->core_signal = bfd_get_16 (abfd, note->descdata + 12); /* `pr_pid' is at offset 24. */ elf_tdata (abfd)->core_lwpid = bfd_get_32 (abfd, note->descdata + 24); /* `pr_reg' is at offset 72. */ offset = 72; /* Most grok_prstatus implementations set `raw_size' to the size of the pr_reg field. For Linux/FRV, we set `raw_size' to be the size of `pr_reg' plus the size of `pr_exec_fdpic_loadmap' and `pr_interp_fdpic_loadmap', both of which (by design) immediately follow `pr_reg'. This will allow these fields to be viewed by GDB as registers. `pr_reg' is 184 bytes long. `pr_exec_fdpic_loadmap' and `pr_interp_fdpic_loadmap' are 4 bytes each. */ raw_size = 184 + 4 + 4; break; } /* Make a ".reg/999" section. */ return _bfd_elfcore_make_pseudosection (abfd, ".reg", raw_size, note->descpos + offset); } static bfd_boolean elf32_frv_grok_psinfo (bfd *abfd, Elf_Internal_Note *note) { switch (note->descsz) { default: return FALSE; /* The Linux/FRV elf_prpsinfo struct is 124 bytes long. */ case 124: /* `pr_fname' is found at offset 28 and is 16 bytes long. */ elf_tdata (abfd)->core_program = _bfd_elfcore_strndup (abfd, note->descdata + 28, 16); /* `pr_psargs' is found at offset 44 and is 80 bytes long. */ elf_tdata (abfd)->core_command = _bfd_elfcore_strndup (abfd, note->descdata + 44, 80); } /* Note that for some reason, a spurious space is tacked onto the end of the args in some (at least one anyway) implementations, so strip it off if it exists. */ { char *command = elf_tdata (abfd)->core_command; int n = strlen (command); if (0 < n && command[n - 1] == ' ') command[n - 1] = '\0'; } return TRUE; } #define ELF_ARCH bfd_arch_frv #define ELF_TARGET_ID FRV_ELF_DATA #define ELF_MACHINE_CODE EM_CYGNUS_FRV #define ELF_MAXPAGESIZE 0x1000 #define TARGET_BIG_SYM bfd_elf32_frv_vec #define TARGET_BIG_NAME "elf32-frv" #define elf_info_to_howto frv_info_to_howto_rela #define elf_backend_relocate_section elf32_frv_relocate_section #define elf_backend_gc_mark_hook elf32_frv_gc_mark_hook #define elf_backend_check_relocs elf32_frv_check_relocs #define elf_backend_object_p elf32_frv_object_p #define elf_backend_add_symbol_hook elf32_frv_add_symbol_hook #define elf_backend_can_gc_sections 1 #define elf_backend_rela_normal 1 #define bfd_elf32_bfd_reloc_type_lookup frv_reloc_type_lookup #define bfd_elf32_bfd_reloc_name_lookup frv_reloc_name_lookup #define bfd_elf32_bfd_set_private_flags frv_elf_set_private_flags #define bfd_elf32_bfd_copy_private_bfd_data frv_elf_copy_private_bfd_data #define bfd_elf32_bfd_merge_private_bfd_data frv_elf_merge_private_bfd_data #define bfd_elf32_bfd_print_private_bfd_data frv_elf_print_private_bfd_data #define elf_backend_want_got_sym 1 #define elf_backend_got_header_size 0 #define elf_backend_want_got_plt 0 #define elf_backend_plt_readonly 1 #define elf_backend_want_plt_sym 0 #define elf_backend_plt_header_size 0 #define elf_backend_finish_dynamic_sections \ elf32_frv_finish_dynamic_sections #define elf_backend_grok_prstatus elf32_frv_grok_prstatus #define elf_backend_grok_psinfo elf32_frv_grok_psinfo #include "elf32-target.h" #undef ELF_MAXPAGESIZE #define ELF_MAXPAGESIZE 0x4000 #undef TARGET_BIG_SYM #define TARGET_BIG_SYM bfd_elf32_frvfdpic_vec #undef TARGET_BIG_NAME #define TARGET_BIG_NAME "elf32-frvfdpic" #undef elf32_bed #define elf32_bed elf32_frvfdpic_bed #undef elf_info_to_howto_rel #define elf_info_to_howto_rel frvfdpic_info_to_howto_rel #undef bfd_elf32_bfd_link_hash_table_create #define bfd_elf32_bfd_link_hash_table_create \ frvfdpic_elf_link_hash_table_create #undef elf_backend_always_size_sections #define elf_backend_always_size_sections \ elf32_frvfdpic_always_size_sections #undef elf_backend_modify_program_headers #define elf_backend_modify_program_headers \ elf32_frvfdpic_modify_program_headers #undef bfd_elf32_bfd_copy_private_bfd_data #define bfd_elf32_bfd_copy_private_bfd_data \ elf32_frvfdpic_copy_private_bfd_data #undef elf_backend_create_dynamic_sections #define elf_backend_create_dynamic_sections \ elf32_frvfdpic_create_dynamic_sections #undef elf_backend_adjust_dynamic_symbol #define elf_backend_adjust_dynamic_symbol \ elf32_frvfdpic_adjust_dynamic_symbol #undef elf_backend_size_dynamic_sections #define elf_backend_size_dynamic_sections \ elf32_frvfdpic_size_dynamic_sections #undef bfd_elf32_bfd_relax_section #define bfd_elf32_bfd_relax_section \ elf32_frvfdpic_relax_section #undef elf_backend_finish_dynamic_symbol #define elf_backend_finish_dynamic_symbol \ elf32_frvfdpic_finish_dynamic_symbol #undef elf_backend_finish_dynamic_sections #define elf_backend_finish_dynamic_sections \ elf32_frvfdpic_finish_dynamic_sections #undef elf_backend_discard_info #define elf_backend_discard_info \ frvfdpic_elf_discard_info #undef elf_backend_can_make_relative_eh_frame #define elf_backend_can_make_relative_eh_frame \ frvfdpic_elf_use_relative_eh_frame #undef elf_backend_can_make_lsda_relative_eh_frame #define elf_backend_can_make_lsda_relative_eh_frame \ frvfdpic_elf_use_relative_eh_frame #undef elf_backend_encode_eh_address #define elf_backend_encode_eh_address \ frvfdpic_elf_encode_eh_address #undef elf_backend_may_use_rel_p #define elf_backend_may_use_rel_p 1 #undef elf_backend_may_use_rela_p #define elf_backend_may_use_rela_p 1 /* We use REL for dynamic relocations only. */ #undef elf_backend_default_use_rela_p #define elf_backend_default_use_rela_p 1 #undef elf_backend_omit_section_dynsym #define elf_backend_omit_section_dynsym _frvfdpic_link_omit_section_dynsym #include "elf32-target.h"
bsd-3-clause
endlessm/chromium-browser
third_party/webgl/src/conformance-suites/2.0.0/conformance2/textures/canvas/tex-2d-rgba4-rgba-unsigned_byte.html
1879
<!-- Copyright (c) 2015 The Khronos Group Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and/or associated documentation files (the "Materials"), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Materials. THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. --> <!-- This file is auto-generated from py/tex_image_test_generator.py DO NOT EDIT! --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="../../../resources/js-test-style.css"/> <script src="../../../js/js-test-pre.js"></script> <script src="../../../js/webgl-test-utils.js"></script> <script src="../../../js/tests/tex-image-and-sub-image-utils.js"></script> <script src="../../../js/tests/tex-image-and-sub-image-2d-with-canvas.js"></script> </head> <body> <canvas id="example" width="32" height="32"></canvas> <div id="description"></div> <div id="console"></div> <script> "use strict"; function testPrologue(gl) { return true; } generateTest("RGBA4", "RGBA", "UNSIGNED_BYTE", testPrologue, "../../../resources/", 2)(); </script> </body> </html>
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/browser/policy/client_data_delegate_android_unittest.cc
1720
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/client_data_delegate_android.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/system/sys_info.h" #include "base/test/task_environment.h" #include "components/policy/core/common/cloud/cloud_policy_util.h" #include "components/policy/proto/device_management_backend.pb.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { TEST(ClientDataDelegateAndroidTest, FillRegisterBrowserRequest) { base::test::TaskEnvironment task_environment; ClientDataDelegateAndroid client_data_delegate; enterprise_management::RegisterBrowserRequest request; client_data_delegate.FillRegisterBrowserRequest(&request, base::DoNothing()); task_environment.RunUntilIdle(); base::SysInfo::HardwareInfo hardware_info; base::SysInfo::GetHardwareInfo(base::BindOnce( [](base::SysInfo::HardwareInfo* target_info, base::SysInfo::HardwareInfo info) { *target_info = std::move(info); }, &hardware_info)); task_environment.RunUntilIdle(); EXPECT_FALSE(request.device_model().empty()); EXPECT_EQ(request.device_model(), hardware_info.model); EXPECT_FALSE(request.brand_name().empty()); EXPECT_EQ(request.brand_name(), hardware_info.manufacturer); // Fields that shouldn't be filled on Android due to Privacy concerns. EXPECT_TRUE(request.machine_name().empty()); EXPECT_TRUE(request.browser_device_identifier().computer_name().empty()); EXPECT_TRUE(request.browser_device_identifier().serial_number().empty()); } } // namespace policy
bsd-3-clause
youtube/cobalt
third_party/llvm-project/libcxx/test/libcxx/utilities/utility/__is_inplace_type.pass.cpp
1436
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // template <class _Tp> using __is_inplace_type #include <utility> struct S {}; int main() { using T = std::in_place_type_t<int>; static_assert( std::__is_inplace_type<T>::value, ""); static_assert( std::__is_inplace_type<const T>::value, ""); static_assert( std::__is_inplace_type<const volatile T>::value, ""); static_assert( std::__is_inplace_type<T&>::value, ""); static_assert( std::__is_inplace_type<const T&>::value, ""); static_assert( std::__is_inplace_type<const volatile T&>::value, ""); static_assert( std::__is_inplace_type<T&&>::value, ""); static_assert( std::__is_inplace_type<const T&&>::value, ""); static_assert( std::__is_inplace_type<const volatile T&&>::value, ""); static_assert(!std::__is_inplace_type<std::in_place_index_t<0>>::value, ""); static_assert(!std::__is_inplace_type<std::in_place_t>::value, ""); static_assert(!std::__is_inplace_type<void>::value, ""); static_assert(!std::__is_inplace_type<int>::value, ""); static_assert(!std::__is_inplace_type<S>::value, ""); }
bsd-3-clause
ChromeDevTools/devtools-frontend
node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts
594
import { TSESTree } from '@typescript-eslint/types'; import { DefinitionType } from './DefinitionType'; import { DefinitionBase } from './DefinitionBase'; declare class VariableDefinition extends DefinitionBase<DefinitionType.Variable, TSESTree.VariableDeclarator, TSESTree.VariableDeclaration, TSESTree.Identifier> { constructor(name: TSESTree.Identifier, node: VariableDefinition['node'], decl: TSESTree.VariableDeclaration); readonly isTypeDefinition = false; readonly isVariableDefinition = true; } export { VariableDefinition }; //# sourceMappingURL=VariableDefinition.d.ts.map
bsd-3-clause
bauhouse/sym-intranet
symphony/assets/symphony.orderable.js
3588
/*----------------------------------------------------------------------------- Orderable plugin -----------------------------------------------------------------------------*/ jQuery.fn.symphonyOrderable = function(custom_settings) { var objects = this; var settings = { items: 'li', handles: '*', delay_initialize: false }; jQuery.extend(settings, custom_settings); /*------------------------------------------------------------------------- Orderable -------------------------------------------------------------------------*/ objects = objects.map(function() { var object = this; var state = null; var start = function() { state = { item: jQuery(this).parents(settings.items), min: null, max: null, delta: 0 }; jQuery(document).mousemove(change); jQuery(document).mouseup(stop); jQuery(document).mousemove(); return false; }; var change = function(event) { var item = state.item; var target, next, top = event.pageY; var a = item.height(); var b = item.offset().top; var prev = item.prev(); state.min = Math.min(b, a + (prev.size() > 0 ? prev.offset().top : -Infinity)); state.max = Math.max(a + b, b + (item.next().height() || Infinity)); if (!object.is('.ordering')) { object.addClass('ordering'); item.addClass('ordering'); object.trigger('orderstart', [state.item]); } if (top < state.min) { target = item.prev(settings.items); while (true) { state.delta--; next = target.prev(settings.items); if (next.length === 0 || top >= (state.min -= next.height())) { item.insertBefore(target); break; } target = next; } } else if (top > state.max) { target = item.next(settings.items); while (true) { state.delta++; next = target.next(settings.items); if (next.length === 0 || top <= (state.max += next.height())) { item.insertAfter(target); break; } target = next; } } object.trigger('orderchange', [state.item]); return false; }; var stop = function() { jQuery(document).unbind('mousemove', change); jQuery(document).unbind('mouseup', stop); if (state != null) { object.removeClass('ordering'); state.item.removeClass('ordering'); object.trigger('orderstop', [state.item]); state = null; } return false; }; /*-------------------------------------------------------------------*/ if (object instanceof jQuery === false) { object = jQuery(object); } object.orderable = { cancel: function() { jQuery(document).unbind('mousemove', change); jQuery(document).unbind('mouseup', stop); if (state != null) { object.removeClass('ordering'); state.item.removeClass('ordering'); object.trigger('ordercancel', [state.item]); state = null; } }, initialize: function() { object.addClass('orderable'); object.find(settings.items).each(function() { var item = jQuery(this); var handle = item.find(settings.handles); handle.unbind('mousedown', start); handle.bind('mousedown', start); }); } }; if (settings.delay_initialize !== true) { object.orderable.initialize(); } return object; }); return objects; }; /*---------------------------------------------------------------------------*/
mit
parjong/coreclr
src/mscorlib/shared/System/IO/Path.cs
24186
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. public static partial class Path { // Public static readonly variant of the separators. The Path implementation itself is using // internal const variant of the separators for better performance. public static readonly char DirectorySeparatorChar = PathInternal.DirectorySeparatorChar; public static readonly char AltDirectorySeparatorChar = PathInternal.AltDirectorySeparatorChar; public static readonly char VolumeSeparatorChar = PathInternal.VolumeSeparatorChar; public static readonly char PathSeparator = PathInternal.PathSeparator; // For generating random file names // 8 random bytes provides 12 chars in our encoding for the 8.3 name. private const int KeyLength = 8; [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] public static readonly char[] InvalidPathChars = GetInvalidPathChars(); // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { PathInternal.CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (path == null) return null; if (PathInternal.IsEffectivelyEmpty(path)) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); PathInternal.CheckInvalidPathChars(path); path = PathInternal.NormalizeDirectorySeparators(path); int root = PathInternal.GetRootLength(path); int i = path.Length; if (i > root) { while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } return null; } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. public static string GetExtension(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. public static string GetFileName(string path) { if (path == null) return null; int offset = PathInternal.FindFileNameIndex(path); int count = path.Length - offset; return path.Substring(offset, count); } public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; int length = path.Length; int offset = PathInternal.FindFileNameIndex(path); int end = path.LastIndexOf('.', length - 1, length - offset); return end == -1 ? path.Substring(offset) : // No extension was found path.Substring(offset, end - offset); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static unsafe string GetRandomFileName() { byte* pKey = stackalloc byte[KeyLength]; Interop.GetRandomBytes(pKey, KeyLength); const int RandomFileNameLength = 12; char* pRandomFileName = stackalloc char[RandomFileNameLength]; Populate83FileNameFromRandomBytes(pKey, KeyLength, pRandomFileName, RandomFileNameLength); return new string(pRandomFileName, 0, RandomFileNameLength); } /// <summary> /// Returns true if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// Returns false if the path specified is relative to the current drive or working directory. /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths <see cref="Path.IsPathRooted(string)"/> are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="path"/> is null. /// </exception> public static bool IsPathFullyQualified(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } return !PathInternal.IsPartiallyQualified(path); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. public static bool HasExtension(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2)); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3)); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(string path1, string path2, string path3, string path4) { if (path1 == null || path2 == null || path3 == null || path4 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4)); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); PathInternal.CheckInvalidPathChars(path4); return CombineNoChecks(path1, path2, path3, path4); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException(nameof(paths)); } int finalSize = 0; int firstComponent = 0; // We have two passes, the first calculates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException(nameof(paths)); } if (paths[i].Length == 0) { continue; } PathInternal.CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(PathInternal.DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return PathInternal.IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + PathInternal.DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + PathInternal.DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + PathInternal.DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(PathInternal.DirectorySeparatorChar) .Append(path2) .Append(PathInternal.DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static string CombineNoChecks(string path1, string path2, string path3, string path4) { if (path1.Length == 0) return CombineNoChecks(path2, path3, path4); if (path2.Length == 0) return CombineNoChecks(path1, path3, path4); if (path3.Length == 0) return CombineNoChecks(path1, path2, path4); if (path4.Length == 0) return CombineNoChecks(path1, path2, path3); if (IsPathRooted(path4)) return path4; if (IsPathRooted(path3)) return CombineNoChecks(path3, path4); if (IsPathRooted(path2)) return CombineNoChecks(path2, path3, path4); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); bool hasSep3 = PathInternal.IsDirectoryOrVolumeSeparator(path3[path3.Length - 1]); if (hasSep1 && hasSep2 && hasSep3) { // Use string.Concat overload that takes four strings return path1 + path2 + path3 + path4; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + path4.Length + 3); sb.Append(path1); if (!hasSep1) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path2); if (!hasSep2) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path3); if (!hasSep3) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path4); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, char* chars, int charCount) { Debug.Assert(bytes != null); Debug.Assert(chars != null); // This method requires bytes of length 8 and chars of length 12. Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}"); Debug.Assert(charCount == 12, $"Unexpected {nameof(charCount)}"); byte b0 = bytes[0]; byte b1 = bytes[1]; byte b2 = bytes[2]; byte b3 = bytes[3]; byte b4 = bytes[4]; // Consume the 5 Least significant bits of the first 5 bytes chars[0] = s_base32Char[b0 & 0x1F]; chars[1] = s_base32Char[b1 & 0x1F]; chars[2] = s_base32Char[b2 & 0x1F]; chars[3] = s_base32Char[b3 & 0x1F]; chars[4] = s_base32Char[b4 & 0x1F]; // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 chars[5] = s_base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]; chars[6] = s_base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]; // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; chars[7] = s_base32Char[b2]; // Set the file extension separator chars[8] = '.'; // Consume the 5 Least significant bits of the remaining 3 bytes chars[9] = s_base32Char[(bytes[5] & 0x1F)]; chars[10] = s_base32Char[(bytes[6] & 0x1F)]; chars[11] = s_base32Char[(bytes[7] & 0x1F)]; } /// <summary> /// Create a relative path from one path to another. Paths will be resolved before calculating the difference. /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix). /// </summary> /// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param> /// <param name="path">The destination path.</param> /// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception> public static string GetRelativePath(string relativeTo, string path) { return GetRelativePath(relativeTo, path, StringComparison); } private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) { if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo)); if (PathInternal.IsEffectivelyEmpty(path)) throw new ArgumentNullException(nameof(path)); Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); relativeTo = GetFullPath(relativeTo); path = GetFullPath(path); // Need to check if the roots are different- if they are we need to return the "to" path. if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType)) return path; int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase); // If there is nothing in common they can't share the same root, return the "to" path as is. if (commonLength == 0) return path; // Trailing separators aren't significant for comparison int relativeToLength = relativeTo.Length; if (PathInternal.EndsInDirectorySeparator(relativeTo)) relativeToLength--; bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path); int pathLength = path.Length; if (pathEndsInSeparator) pathLength--; // If we have effectively the same path, return "." if (relativeToLength == pathLength && commonLength >= relativeToLength) return "."; // We have the same root, we need to calculate the difference now using the // common Length and Segment count past the length. // // Some examples: // // C:\Foo C:\Bar L3, S1 -> ..\Bar // C:\Foo C:\Foo\Bar L6, S0 -> Bar // C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar // C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar StringBuilder sb = StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length)); // Add parent segments for segments past the common on the "from" path if (commonLength < relativeToLength) { sb.Append(PathInternal.ParentDirectoryPrefix); for (int i = commonLength; i < relativeToLength; i++) { if (PathInternal.IsDirectorySeparator(relativeTo[i])) { sb.Append(PathInternal.ParentDirectoryPrefix); } } } else if (PathInternal.IsDirectorySeparator(path[commonLength])) { // No parent segments and we need to eat the initial separator // (C:\Foo C:\Foo\Bar case) commonLength++; } // Now add the rest of the "to" path, adding back the trailing separator int count = pathLength - commonLength; if (pathEndsInSeparator) count++; sb.Append(path, commonLength, count); return StringBuilderCache.GetStringAndRelease(sb); } // StringComparison and IsCaseSensitive are also available in PathInternal.CaseSensitivity but we are // too low in System.Runtime.Extensions to use it (no FileStream, etc.) /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary> internal static StringComparison StringComparison { get { return IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; } } } }
mit
hyoo/p3_web
public/js/release/d3/src/scale/ordinal.js
3374
// wrapped by build app define("d3/src/scale/ordinal", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ import "../arrays/map"; import "../arrays/range"; import "scale"; d3.scale.ordinal = function() { return d3_scale_ordinal([], {t: "range", a: [[]]}); }; function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map; var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = {t: "range", a: arguments}; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding); range = steps(start + step * padding / 2, step); rangeBand = 0; ranger = {t: "rangePoints", a: arguments}; return scale; }; scale.rangeRoundPoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; // bitwise floor for symmetry range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); rangeBand = 0; ranger = {t: "rangeRoundPoints", a: arguments}; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = {t: "rangeBands", a: arguments}; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = {t: "rangeRoundBands", a: arguments}; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } });
mit
m039/Void
third-party/void-boost/tools/build/src/tools/testing.py
15330
# Status: ported, except for --out-xml # Base revision: 64488 # # Copyright 2005 Dave Abrahams # Copyright 2002, 2003, 2004, 2005, 2010 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # This module implements regression testing framework. It declares a number of # main target rules which perform some action and, if the results are OK, # creates an output file. # # The exact list of rules is: # 'compile' -- creates .test file if compilation of sources was # successful. # 'compile-fail' -- creates .test file if compilation of sources failed. # 'run' -- creates .test file is running of executable produced from # sources was successful. Also leaves behind .output file # with the output from program run. # 'run-fail' -- same as above, but .test file is created if running fails. # # In all cases, presence of .test file is an indication that the test passed. # For more convenient reporting, you might want to use C++ Boost regression # testing utilities (see http://www.boost.org/more/regression.html). # # For historical reason, a 'unit-test' rule is available which has the same # syntax as 'exe' and behaves just like 'run'. # Things to do: # - Teach compiler_status handle Jamfile.v2. # Notes: # - <no-warn> is not implemented, since it is Como-specific, and it is not # clear how to implement it # - std::locale-support is not implemented (it is used in one test). import b2.build.feature as feature import b2.build.type as type import b2.build.targets as targets import b2.build.generators as generators import b2.build.toolset as toolset import b2.tools.common as common import b2.util.option as option import b2.build_system as build_system from b2.manager import get_manager from b2.util import stem, bjam_signature, is_iterable_typed from b2.util.sequence import unique import bjam import re import os.path import sys def init(): pass # Feature controling the command used to lanch test programs. feature.feature("testing.launcher", [], ["free", "optional"]) feature.feature("test-info", [], ["free", "incidental"]) feature.feature("testing.arg", [], ["free", "incidental"]) feature.feature("testing.input-file", [], ["free", "dependency"]) feature.feature("preserve-test-targets", ["on", "off"], ["incidental", "propagated"]) # Register target types. type.register("TEST", ["test"]) type.register("COMPILE", [], "TEST") type.register("COMPILE_FAIL", [], "TEST") type.register("RUN_OUTPUT", ["run"]) type.register("RUN", [], "TEST") type.register("RUN_FAIL", [], "TEST") type.register("LINK", [], "TEST") type.register("LINK_FAIL", [], "TEST") type.register("UNIT_TEST", ["passed"], "TEST") __all_tests = [] # Declare the rules which create main targets. While the 'type' module already # creates rules with the same names for us, we need extra convenience: default # name of main target, so write our own versions. # Helper rule. Create a test target, using basename of first source if no target # name is explicitly passed. Remembers the created target in a global variable. def make_test(target_type, sources, requirements, target_name=None): assert isinstance(target_type, basestring) assert is_iterable_typed(sources, basestring) assert is_iterable_typed(requirements, basestring) assert isinstance(target_type, basestring) or target_type is None if not target_name: target_name = stem(os.path.basename(sources[0])) # Having periods (".") in the target name is problematic because the typed # generator will strip the suffix and use the bare name for the file # targets. Even though the location-prefix averts problems most times it # does not prevent ambiguity issues when referring to the test targets. For # example when using the XML log output. So we rename the target to remove # the periods, and provide an alias for users. real_name = target_name.replace(".", "~") project = get_manager().projects().current() # The <location-prefix> forces the build system for generate paths in the # form '$build_dir/array1.test/gcc/debug'. This is necessary to allow # post-processing tools to work. t = get_manager().targets().create_typed_target( type.type_from_rule_name(target_type), project, real_name, sources, requirements + ["<location-prefix>" + real_name + ".test"], [], []) # The alias to the real target, per period replacement above. if real_name != target_name: get_manager().projects().project_rules().rules["alias"]( target_name, [t]) # Remember the test (for --dump-tests). A good way would be to collect all # given a project. This has some technical problems: e.g. we can not call # this dump from a Jamfile since projects referred by 'build-project' are # not available until the whole Jamfile has been loaded. __all_tests.append(t) return t # Note: passing more that one cpp file here is known to fail. Passing a cpp file # and a library target works. # @bjam_signature((["sources", "*"], ["requirements", "*"], ["target_name", "?"])) def compile(sources, requirements, target_name=None): return make_test("compile", sources, requirements, target_name) @bjam_signature((["sources", "*"], ["requirements", "*"], ["target_name", "?"])) def compile_fail(sources, requirements, target_name=None): return make_test("compile-fail", sources, requirements, target_name) @bjam_signature((["sources", "*"], ["requirements", "*"], ["target_name", "?"])) def link(sources, requirements, target_name=None): return make_test("link", sources, requirements, target_name) @bjam_signature((["sources", "*"], ["requirements", "*"], ["target_name", "?"])) def link_fail(sources, requirements, target_name=None): return make_test("link-fail", sources, requirements, target_name) def handle_input_files(input_files): if len(input_files) > 1: # Check that sorting made when creating property-set instance will not # change the ordering. if sorted(input_files) != input_files: get_manager().errors()("Names of input files must be sorted alphabetically\n" + "due to internal limitations") return ["<testing.input-file>" + f for f in input_files] @bjam_signature((["sources", "*"], ["args", "*"], ["input_files", "*"], ["requirements", "*"], ["target_name", "?"], ["default_build", "*"])) def run(sources, args, input_files, requirements, target_name=None, default_build=[]): if args: requirements.append("<testing.arg>" + " ".join(args)) requirements.extend(handle_input_files(input_files)) return make_test("run", sources, requirements, target_name) @bjam_signature((["sources", "*"], ["args", "*"], ["input_files", "*"], ["requirements", "*"], ["target_name", "?"], ["default_build", "*"])) def run_fail(sources, args, input_files, requirements, target_name=None, default_build=[]): if args: requirements.append("<testing.arg>" + " ".join(args)) requirements.extend(handle_input_files(input_files)) return make_test("run-fail", sources, requirements, target_name) # Register all the rules for name in ["compile", "compile-fail", "link", "link-fail", "run", "run-fail"]: get_manager().projects().add_rule(name, getattr(sys.modules[__name__], name.replace("-", "_"))) # Use 'test-suite' as a synonym for 'alias', for backward compatibility. from b2.build.alias import alias get_manager().projects().add_rule("test-suite", alias) # For all main targets in 'project-module', which are typed targets with type # derived from 'TEST', produce some interesting information. # def dump_tests(): for t in __all_tests: dump_test(t) # Given a project location in normalized form (slashes are forward), compute the # name of the Boost library. # __ln1 = re.compile("/(tools|libs)/(.*)/(test|example)") __ln2 = re.compile("/(tools|libs)/(.*)$") __ln3 = re.compile("(/status$)") def get_library_name(path): assert isinstance(path, basestring) path = path.replace("\\", "/") match1 = __ln1.match(path) match2 = __ln2.match(path) match3 = __ln3.match(path) if match1: return match1.group(2) elif match2: return match2.group(2) elif match3: return "" elif option.get("dump-tests", False, True): # The 'run' rule and others might be used outside boost. In that case, # just return the path, since the 'library name' makes no sense. return path # Was an XML dump requested? __out_xml = option.get("out-xml", False, True) # Takes a target (instance of 'basic-target') and prints # - its type # - its name # - comments specified via the <test-info> property # - relative location of all source from the project root. # def dump_test(target): assert isinstance(target, targets.AbstractTarget) type = target.type() name = target.name() project = target.project() project_root = project.get('project-root') library = get_library_name(os.path.abspath(project.get('location'))) if library: name = library + "/" + name sources = target.sources() source_files = [] for s in sources: if isinstance(s, targets.FileReference): location = os.path.abspath(os.path.join(s.location(), s.name())) source_files.append(os.path.relpath(location, os.path.abspath(project_root))) target_name = project.get('location') + "//" + target.name() + ".test" test_info = target.requirements().get('test-info') test_info = " ".join('"' + ti + '"' for ti in test_info) # If the user requested XML output on the command-line, add the test info to # that XML file rather than dumping them to stdout. #if $(.out-xml) #{ # local nl = " #" ; # .contents on $(.out-xml) += # "$(nl) <test type=\"$(type)\" name=\"$(name)\">" # "$(nl) <target><![CDATA[$(target-name)]]></target>" # "$(nl) <info><![CDATA[$(test-info)]]></info>" # "$(nl) <source><![CDATA[$(source-files)]]></source>" # "$(nl) </test>" # ; # } # else source_files = " ".join('"' + s + '"' for s in source_files) if test_info: print 'boost-test(%s) "%s" [%s] : %s' % (type, name, test_info, source_files) else: print 'boost-test(%s) "%s" : %s' % (type, name, source_files) # Register generators. Depending on target type, either 'expect-success' or # 'expect-failure' rule will be used. generators.register_standard("testing.expect-success", ["OBJ"], ["COMPILE"]) generators.register_standard("testing.expect-failure", ["OBJ"], ["COMPILE_FAIL"]) generators.register_standard("testing.expect-success", ["RUN_OUTPUT"], ["RUN"]) generators.register_standard("testing.expect-failure", ["RUN_OUTPUT"], ["RUN_FAIL"]) generators.register_standard("testing.expect-success", ["EXE"], ["LINK"]) generators.register_standard("testing.expect-failure", ["EXE"], ["LINK_FAIL"]) # Generator which runs an EXE and captures output. generators.register_standard("testing.capture-output", ["EXE"], ["RUN_OUTPUT"]) # Generator which creates a target if sources run successfully. Differs from RUN # in that run output is not captured. The reason why it exists is that the 'run' # rule is much better for automated testing, but is not user-friendly (see # http://article.gmane.org/gmane.comp.lib.boost.build/6353). generators.register_standard("testing.unit-test", ["EXE"], ["UNIT_TEST"]) # FIXME: if those calls are after bjam.call, then bjam will crash # when toolset.flags calls bjam.caller. toolset.flags("testing.capture-output", "ARGS", [], ["<testing.arg>"]) toolset.flags("testing.capture-output", "INPUT_FILES", [], ["<testing.input-file>"]) toolset.flags("testing.capture-output", "LAUNCHER", [], ["<testing.launcher>"]) toolset.flags("testing.unit-test", "LAUNCHER", [], ["<testing.launcher>"]) toolset.flags("testing.unit-test", "ARGS", [], ["<testing.arg>"]) # This is a composing generator to support cases where a generator for the # specified target constructs other targets as well. One such example is msvc's # exe generator that constructs both EXE and PDB targets. type.register("TIME", ["time"]) generators.register_composing("testing.time", [], ["TIME"]) # The following code sets up actions for this module. It's pretty convoluted, # but the basic points is that we most of actions are defined by Jam code # contained in testing-aux.jam, which we load into Jam module named 'testing' def run_path_setup(target, sources, ps): if __debug__: from ..build.property_set import PropertySet assert is_iterable_typed(target, basestring) or isinstance(target, basestring) assert is_iterable_typed(sources, basestring) assert isinstance(ps, PropertySet) # For testing, we need to make sure that all dynamic libraries needed by the # test are found. So, we collect all paths from dependency libraries (via # xdll-path property) and add whatever explicit dll-path user has specified. # The resulting paths are added to the environment on each test invocation. dll_paths = ps.get('dll-path') dll_paths.extend(ps.get('xdll-path')) dll_paths.extend(bjam.call("get-target-variable", sources, "RUN_PATH")) dll_paths = unique(dll_paths) if dll_paths: bjam.call("set-target-variable", target, "PATH_SETUP", common.prepend_path_variable_command( common.shared_library_path_variable(), dll_paths)) def capture_output_setup(target, sources, ps): if __debug__: from ..build.property_set import PropertySet assert is_iterable_typed(target, basestring) assert is_iterable_typed(sources, basestring) assert isinstance(ps, PropertySet) run_path_setup(target[0], sources, ps) if ps.get('preserve-test-targets') == ['off']: bjam.call("set-target-variable", target, "REMOVE_TEST_TARGETS", "1") get_manager().engine().register_bjam_action("testing.capture-output", capture_output_setup) path = os.path.dirname(__file__) import b2.util.os_j get_manager().projects().project_rules()._import_rule("testing", "os.name", b2.util.os_j.name) import b2.tools.common get_manager().projects().project_rules()._import_rule("testing", "common.rm-command", b2.tools.common.rm_command) get_manager().projects().project_rules()._import_rule("testing", "common.file-creation-command", b2.tools.common.file_creation_command) bjam.call("load", "testing", os.path.join(path, "testing-aux.jam")) for name in ["expect-success", "expect-failure", "time"]: get_manager().engine().register_bjam_action("testing." + name) get_manager().engine().register_bjam_action("testing.unit-test", run_path_setup) if option.get("dump-tests", False, True): build_system.add_pre_build_hook(dump_tests)
mit
stevenblaster/crapengine
libraries/bullet/btgui/OpenGLWindow/Shaders/useShadowMapInstancingVS.h
2424
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project static const char* useShadowMapInstancingVertexShader= \ "#version 330 \n" "precision highp float;\n" "layout (location = 0) in vec4 position;\n" "layout (location = 1) in vec4 instance_position;\n" "layout (location = 2) in vec4 instance_quaternion;\n" "layout (location = 3) in vec2 uvcoords;\n" "layout (location = 4) in vec3 vertexnormal;\n" "layout (location = 5) in vec4 instance_color;\n" "layout (location = 6) in vec3 instance_scale;\n" "uniform mat4 ModelViewMatrix;\n" "uniform mat4 ProjectionMatrix;\n" "uniform mat4 DepthBiasModelViewProjectionMatrix;\n" "uniform mat4 MVP;\n" "uniform vec3 lightDirIn;\n" "out vec4 ShadowCoord;\n" "out Fragment\n" "{\n" " vec4 color;\n" "} fragment;\n" "out Vert\n" "{\n" " vec2 texcoord;\n" "} vert;\n" "vec4 quatMul ( in vec4 q1, in vec4 q2 )\n" "{\n" " vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n" " vec4 dt = q1 * q2;\n" " float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n" " return vec4 ( im, re );\n" "}\n" "vec4 quatFromAxisAngle(vec4 axis, in float angle)\n" "{\n" " float cah = cos(angle*0.5);\n" " float sah = sin(angle*0.5);\n" " float d = inversesqrt(dot(axis,axis));\n" " vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n" " return q;\n" "}\n" "//\n" "// vector rotation via quaternion\n" "//\n" "vec4 quatRotate3 ( in vec3 p, in vec4 q )\n" "{\n" " vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n" " return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n" "}\n" "vec4 quatRotate ( in vec4 p, in vec4 q )\n" "{\n" " vec4 temp = quatMul ( q, p );\n" " return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n" "}\n" "out vec3 lightDir,normal,ambient;\n" "void main(void)\n" "{\n" " vec4 q = instance_quaternion;\n" " ambient = vec3(0.3,.3,0.3);\n" " \n" " vec4 worldNormal = (quatRotate3( vertexnormal,q));\n" " \n" " normal = normalize(worldNormal).xyz;\n" " lightDir = lightDirIn;\n" " \n" " vec4 axis = vec4(1,1,1,0);\n" " vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);\n" " vec4 vertexPos = MVP* vec4((instance_position+localcoord).xyz,1);\n" " gl_Position = vertexPos;\n" " ShadowCoord = DepthBiasModelViewProjectionMatrix * vec4((instance_position+localcoord).xyz,1);\n" " fragment.color = instance_color;\n" " vert.texcoord = uvcoords;\n" "}\n" ;
mit
wikimedia/mediawiki-vagrant
puppet/modules/stdlib/spec/acceptance/is_string_spec.rb
2778
#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do describe 'success' do it 'is_strings arrays' do pp = <<-EOS $a = ['aaa.com','bbb','ccc'] $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/Notice: output correct/) end end it 'is_strings true' do pp = <<-EOS $a = true $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/Notice: output correct/) end end it 'is_strings strings' do pp = <<-EOS $a = "aoeu" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/is_string is true/) end end it 'is_strings number strings' do pp = <<-EOS $a = "3" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/is_string is false/) end end it 'is_strings floats' do pp = <<-EOS $a = 3.5 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/Notice: output correct/) end end it 'is_strings integers' do pp = <<-EOS $a = 3 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/Notice: output correct/) end end it 'is_strings hashes' do pp = <<-EOS $a = {'aaa'=>'www.com'} $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/Notice: output correct/) end end it 'is_strings undef' do pp = <<-EOS $a = undef $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) EOS apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(/is_string is true/) end end end describe 'failure' do it 'handles improper argument counts' end end
mit
stanislaw/EKAlgorithms
EKAlgorithms/Data Structures/LinkedList/EKLinkedList.h
852
// // LinkedList.h // EKAlgorithms // // Created by Evgeny Karkan on 07.11.13. // Copyright (c) 2013 EvgenyKarkan. All rights reserved. // @class EKNode; @interface EKLinkedList : NSObject @property (nonatomic, strong) EKNode *head; @property (nonatomic, strong) EKNode *tail; @property (nonatomic, strong) EKNode *current; - (instancetype)initWithHead:(NSObject *)value; - (void)addToFront:(NSObject *)value; - (void)addToBack:(NSObject *)value; - (void)insertObject:(NSObject *)object atIndex:(NSUInteger)index; - (NSObject *)first; - (NSObject *)currentValue; - (NSObject *)next; - (NSObject *)previous; - (NSUInteger)count; - (NSObject *)objectAtIndex:(NSUInteger)index; - (NSArray *)findObject:(NSObject *)object; - (BOOL)removeCurrent; - (BOOL)removeObjectAtIndex:(NSUInteger)index; - (void)printList; - (void)reverseList; @end
mit
smatthias/tausendkind
vendor/sonata-project/admin-bundle/Mapper/BaseMapper.php
1668
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Mapper; use Sonata\AdminBundle\Admin\AdminInterface; use Sonata\AdminBundle\Builder\BuilderInterface; /** * This class is used to simulate the Form API. * * @author Thomas Rabaix <[email protected]> */ abstract class BaseMapper { /** * @var AdminInterface */ protected $admin; /** * @var BuilderInterface */ protected $builder; /** * @param BuilderInterface $builder * @param AdminInterface $admin */ public function __construct(BuilderInterface $builder, AdminInterface $admin) { $this->builder = $builder; $this->admin = $admin; } /** * @return AdminInterface */ public function getAdmin() { return $this->admin; } /** * @param string $key * * @return mixed */ abstract public function get($key); /** * @param string $key * * @return bool */ abstract public function has($key); /** * @param string $key * * @return $this */ abstract public function remove($key); // To be uncommented on 4.0. /** * Returns configured keys. * * @return string[] */ //abstract public function keys(); /** * @param array $keys field names * * @return $this */ abstract public function reorder(array $keys); }
mit
bvernoux/micropython
ports/stm32/usb.h
2800
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014, 2015 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_STM32_USB_H #define MICROPY_INCLUDED_STM32_USB_H #include "usbd_cdc_msc_hid0.h" #define PYB_USB_FLAG_USB_MODE_CALLED (0x0002) typedef enum { PYB_USB_STORAGE_MEDIUM_NONE = 0, PYB_USB_STORAGE_MEDIUM_FLASH, PYB_USB_STORAGE_MEDIUM_SDCARD, } pyb_usb_storage_medium_t; typedef enum { USB_PHY_FS_ID = 0, USB_PHY_HS_ID = 1, } USB_PHY_ID; typedef struct _pyb_usb_vcp_obj_t pyb_usb_vcp_obj_t; extern mp_uint_t pyb_usb_flags; extern pyb_usb_storage_medium_t pyb_usb_storage_medium; extern const struct _mp_rom_obj_tuple_t pyb_usb_hid_mouse_obj; extern const struct _mp_rom_obj_tuple_t pyb_usb_hid_keyboard_obj; extern const mp_obj_type_t pyb_usb_vcp_type; extern const mp_obj_type_t pyb_usb_hid_type; MP_DECLARE_CONST_FUN_OBJ_KW(pyb_usb_mode_obj); MP_DECLARE_CONST_FUN_OBJ_0(pyb_have_cdc_obj); // deprecated MP_DECLARE_CONST_FUN_OBJ_1(pyb_hid_send_report_obj); // deprecated void pyb_usb_init0(void); int pyb_usb_dev_detect(void); bool pyb_usb_dev_init(int dev_id, uint16_t vid, uint16_t pid, uint8_t mode, size_t msc_n, const void *msc_unit, USBD_HID_ModeInfoTypeDef *hid_info); void pyb_usb_dev_deinit(void); bool usb_vcp_is_enabled(void); int usb_vcp_recv_byte(uint8_t *c); // if a byte is available, return 1 and put the byte in *c, else return 0 void usb_vcp_send_strn(const char *str, int len); void usb_vcp_attach_to_repl(const pyb_usb_vcp_obj_t *self, bool attached); void pyb_usb_host_init(void); void pyb_usb_host_process(void); uint pyb_usb_host_get_keyboard(void); #endif // MICROPY_INCLUDED_STM32_USB_H
mit
frangucc/gamify
www/sandbox/pals/app/bower_components/ionic/js/angular/directive/item.js
1904
var ITEM_TPL_CONTENT_ANCHOR = '<a class="item-content" ng-href="{{$href()}}" target="{{$target()}}"></a>'; var ITEM_TPL_CONTENT = '<div class="item-content"></div>'; /** * @ngdoc directive * @name ionItem * @parent ionic.directive:ionList * @module ionic * @restrict E * Creates a list-item that can easily be swiped, * deleted, reordered, edited, and more. * * See {@link ionic.directive:ionList} for a complete example & explanation. * * Can be assigned any item class name. See the * [list CSS documentation](/docs/components/#list). * * @usage * * ```html * <ion-list> * <ion-item>Hello!</ion-item> * </ion-list> * ``` */ IonicModule .directive('ionItem', [ '$animate', '$compile', function($animate, $compile) { return { restrict: 'E', controller: ['$scope', '$element', function($scope, $element) { this.$scope = $scope; this.$element = $element; }], scope: true, compile: function($element, $attrs) { var isAnchor = angular.isDefined($attrs.href) || angular.isDefined($attrs.ngHref) || angular.isDefined($attrs.uiSref); var isComplexItem = isAnchor || //Lame way of testing, but we have to know at compile what to do with the element /ion-(delete|option|reorder)-button/i.test($element.html()); if (isComplexItem) { var innerElement = jqLite(isAnchor ? ITEM_TPL_CONTENT_ANCHOR : ITEM_TPL_CONTENT); innerElement.append($element.contents()); $element.append(innerElement); $element.addClass('item item-complex'); } else { $element.addClass('item'); } return function link($scope, $element, $attrs) { $scope.$href = function() { return $attrs.href || $attrs.ngHref; }; $scope.$target = function() { return $attrs.target || '_self'; }; }; } }; }]);
mit
api-platform/core
src/Core/Api/FilterInterface.php
1670
<?php /* * This file is part of the API Platform project. * * (c) Kévin Dunglas <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace ApiPlatform\Core\Api; /** * Filters applicable on a resource. * * @author Kévin Dunglas <[email protected]> */ interface FilterInterface { /** * Gets the description of this filter for the given resource. * * Returns an array with the filter parameter names as keys and array with the following data as values: * - property: the property where the filter is applied * - type: the type of the filter * - required: if this filter is required * - strategy (optional): the used strategy * - is_collection (optional): is this filter is collection * - swagger (optional): additional parameters for the path operation, * e.g. 'swagger' => [ * 'description' => 'My Description', * 'name' => 'My Name', * 'type' => 'integer', * ] * - openapi (optional): additional parameters for the path operation in the version 3 spec, * e.g. 'openapi' => [ * 'description' => 'My Description', * 'name' => 'My Name', * 'schema' => [ * 'type' => 'integer', * ] * ] * The description can contain additional data specific to a filter. * * @see \ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer::getFiltersParameters */ public function getDescription(string $resourceClass): array; }
mit
ndnurun/nextdeploy
vagrant/modules/ossec/spec/classes/init_spec.rb
142
require 'spec_helper' describe 'ossec' do context 'with defaults for all parameters' do it { should contain_class('ossec') } end end
mit
whbruce/upm
src/max5487/max5487.hpp
3393
/* * Author: Yevgeniy Kiveisha <[email protected]> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <string> #include <mraa/aio.hpp> #include <mraa/gpio.hpp> #include <mraa/spi.hpp> #define HIGH 1 #define LOW 0 namespace upm { /** * @brief MAX5487 Digital Potentiometer library * @defgroup max5487 libupm-max5487 * @ingroup maxim spi digipot */ /** * @library max5487 * @sensor max5487 * @comname Digital Potentiometer * @type digipot * @man maxim * @con spi * @web https://www.maximintegrated.com/en/products/analog/data-converters/digital-potentiometers/MAX5487.html * * @brief API for the MAX5487 SPI Digital Potentiometer * * Maxim Integrated* * [MAX5487](http://datasheets.maximintegrated.com/en/ds/MAX5487-MAX5489.pdf) * is a dual, 256-tap, nonvolatile, SPI, linear-taper digital * potentiometer. This module was tested on the Maxim Integrated [MAX5487PMB1 * PMOD module](http://datasheets.maximintegrated.com/en/ds/MAX5487PMB1.pdf) * from the analog PMOD kit. * * @snippet max5487.cxx Interesting */ class MAX5487 { public: static const uint8_t R_WR_WIPER_A = 0x01; static const uint8_t R_WR_WIPER_B = 0x02; /** * Instantiates an MAX5487 object * * @param csn CSN to use, if any; by default, ICSP CS (-1) is used */ MAX5487 (int csn = -1); /** * MAX5487 object destructor, closes all IO connections * no more needed as the connections will be closed when * m_spi and m_csnPinCtx will go out of scope * ~MAX5487 (); **/ /** * Sets a wiper for port A. */ void setWiperA (uint8_t wiper); /** * Sets a wiper for port B. */ void setWiperB (uint8_t wiper); /** * Returns the name of the component */ std::string name() { return m_name; } private: std::string m_name; mraa::Spi m_spi; mraa::Gpio m_csnPinCtx; /** * Sets the chip select pin to LOW */ mraa::Result CSOn (); /** * Sets the chip select pin to HIGH */ mraa::Result CSOff (); }; }
mit
rainlike/justshop
vendor/sylius/sylius/src/Sylius/Bundle/ThemeBundle/Context/ThemeContextInterface.php
598
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\ThemeBundle\Context; use Sylius\Bundle\ThemeBundle\Model\ThemeInterface; /** * @author Kamil Kokot <[email protected]> */ interface ThemeContextInterface { /** * Should not throw any exception if failed to get theme. * * @return ThemeInterface|null */ public function getTheme(): ?ThemeInterface; }
mit
Dackng/eh-unmsm-client
node_modules/@angularclass/hmr/README.md
3922
<p align="center"> <a href="http://courses.angularclass.com/courses/angular-2-fundamentals" target="_blank"> <img width="438" alt="Angular 2 Fundamentals" src="https://cloud.githubusercontent.com/assets/1016365/17200649/085798c6-543c-11e6-8ad0-2484f0641624.png"> </a> </p> --- # Angular 2 Hot Module Replacement > Angular2-HMR `npm install @angularclass/hmr @angularclass/hmr-loader` Please see repository [AngularClass/angular2-seed](https://github.com/AngularClass/angular2-seed) for a working example. Also download [AngularClass/angular2-hmr-loader](https://github.com/AngularClass/angular2-hmr-loader) ![hmr-state-dom](https://cloud.githubusercontent.com/assets/1016365/18380378/e573320e-762b-11e6-99e0-cc110ffacc6a.gif) `main.browser.ts` ```typescript import { removeNgStyles, createNewHosts, bootloader } from '@angularclass/hmr'; @NgModule({ bootstrap: [ App ], declarations: [ App ], imports: [ // Angular 2 BrowserModule, FormsModule, HttpModule, RouterModule.forRoot([], { useHash: true }), // app appModule // vendors ], providers: [] }) class MainModule { constructor(public appRef: ApplicationRef) {} hmrOnInit(store) { if (!store || !store.state) return; console.log('HMR store', store); console.log('store.state.data:', store.state.data) // inject AppStore here and update it // this.AppStore.update(store.state) if ('restoreInputValues' in store) { store.restoreInputValues(); } // change detection this.appRef.tick(); delete store.state; delete store.restoreInputValues; } hmrOnDestroy(store) { var cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement); // recreate elements store.disposeOldHosts = createNewHosts(cmpLocation) // inject your AppStore and grab state then set it on store // var appState = this.AppStore.get() store.state = {data: 'yolo'}; // store.state = Object.assign({}, appState) // save input values store.restoreInputValues = createInputTransfer(); // remove styles removeNgStyles(); } hmrAfterDestroy(store) { // display new elements store.disposeOldHosts() delete store.disposeOldHosts; // anything you need done the component is removed } } export function main() { return platformBrowserDynamic().bootstrapModule(MainModule); } // boot on document ready bootloader(main); ``` `bootloader` is only needed to detect that the dom is ready before bootstraping otherwise bootstrap. This is needed because that dom is already ready during reloading. ## Important Helpers * **removeNgStyles**: remove angular styles * **createNewHosts and disposeOldHosts**: recreate root elements for bootstrapping * **bootloader**: boot on document ready or boot if it's already ready * **createInputTransfer** and **restoreInputValues**: transfer input DOM state during replacement ## Production In production you only need bootloader which just does this: ```typescript export function bootloader(main) { if (document.readyState === 'complete') { main() } else { document.addEventListener('DOMContentLoaded', main); } } ``` You would bootstrap your app the normal way, in production, afer dom is ready. Also, in production, you should remove the loader: ```es6 { test: /\.ts$/, loaders: [ 'awesome-typescript-loader', ].concat(prod ? [] : '@angularclass/hmr-loader') }, ``` ___ enjoy — **AngularClass** <br><br> [![AngularClass](https://cloud.githubusercontent.com/assets/1016365/9863770/cb0620fc-5af7-11e5-89df-d4b0b2cdfc43.png "Angular Class")](https://angularclass.com) ##[AngularClass](https://angularclass.com) > Learn AngularJS, Angular 2, and Modern Web Development from the best. > Looking for corporate Angular training, want to host us, or Angular consulting? [email protected]
mit
smrq/DefinitelyTyped
types/react-icons/go/light-bulb.d.ts
162
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class GoLightBulb extends React.Component<IconBaseProps, any> { }
mit
jpweeks/pixi.js
src/particles/webgl/ParticleBuffer.js
6828
import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../core/utils/createIndicesForQuads'; /** * @author Mat Groves * * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/ * for creating the original pixi version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that * they now share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's ParticleBuffer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java */ /** * The particle buffer manages the static and dynamic buffers for a particle container. * * @class * @private * @memberof PIXI */ export default class ParticleBuffer { /** * @param {WebGLRenderingContext} gl - The rendering context. * @param {object} properties - The properties to upload. * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. * @param {number} size - The size of the batch. */ constructor(gl, properties, dynamicPropertyFlags, size) { /** * The current WebGL drawing context. * * @member {WebGLRenderingContext} */ this.gl = gl; /** * Size of a single vertex. * * @member {number} */ this.vertSize = 2; /** * Size of a single vertex in bytes. * * @member {number} */ this.vertByteSize = this.vertSize * 4; /** * The number of particles the buffer can hold * * @member {number} */ this.size = size; /** * A list of the properties that are dynamic. * * @member {object[]} */ this.dynamicProperties = []; /** * A list of the properties that are static. * * @member {object[]} */ this.staticProperties = []; for (let i = 0; i < properties.length; ++i) { let property = properties[i]; // Make copy of properties object so that when we edit the offset it doesn't // change all other instances of the object literal property = { attribute: property.attribute, size: property.size, uploadFunction: property.uploadFunction, offset: property.offset, }; if (dynamicPropertyFlags[i]) { this.dynamicProperties.push(property); } else { this.staticProperties.push(property); } } this.staticStride = 0; this.staticBuffer = null; this.staticData = null; this.dynamicStride = 0; this.dynamicBuffer = null; this.dynamicData = null; this.initBuffers(); } /** * Sets up the renderer context and necessary buffers. * * @private */ initBuffers() { const gl = this.gl; let dynamicOffset = 0; /** * Holds the indices of the geometry (quads) to draw * * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); this.dynamicStride = 0; for (let i = 0; i < this.dynamicProperties.length; ++i) { const property = this.dynamicProperties[i]; property.offset = dynamicOffset; dynamicOffset += property.size; this.dynamicStride += property.size; } this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); this.dynamicBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); // static // let staticOffset = 0; this.staticStride = 0; for (let i = 0; i < this.staticProperties.length; ++i) { const property = this.staticProperties[i]; property.offset = staticOffset; staticOffset += property.size; this.staticStride += property.size; } this.staticData = new Float32Array(this.size * this.staticStride * 4); this.staticBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); this.vao = new glCore.VertexArrayObject(gl) .addIndex(this.indexBuffer); for (let i = 0; i < this.dynamicProperties.length; ++i) { const property = this.dynamicProperties[i]; this.vao.addAttribute( this.dynamicBuffer, property.attribute, gl.FLOAT, false, this.dynamicStride * 4, property.offset * 4 ); } for (let i = 0; i < this.staticProperties.length; ++i) { const property = this.staticProperties[i]; this.vao.addAttribute( this.staticBuffer, property.attribute, gl.FLOAT, false, this.staticStride * 4, property.offset * 4 ); } } /** * Uploads the dynamic properties. * * @param {PIXI.DisplayObject[]} children - The children to upload. * @param {number} startIndex - The index to start at. * @param {number} amount - The number to upload. */ uploadDynamic(children, startIndex, amount) { for (let i = 0; i < this.dynamicProperties.length; i++) { const property = this.dynamicProperties[i]; property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); } this.dynamicBuffer.upload(); } /** * Uploads the static properties. * * @param {PIXI.DisplayObject[]} children - The children to upload. * @param {number} startIndex - The index to start at. * @param {number} amount - The number to upload. */ uploadStatic(children, startIndex, amount) { for (let i = 0; i < this.staticProperties.length; i++) { const property = this.staticProperties[i]; property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); } this.staticBuffer.upload(); } /** * Destroys the ParticleBuffer. * */ destroy() { this.dynamicProperties = null; this.dynamicData = null; this.dynamicBuffer.destroy(); this.staticProperties = null; this.staticData = null; this.staticBuffer.destroy(); } }
mit
esdrubal/referencesource
System/compmod/system/codedom/compiler/ICodeCompiler.cs
3460
//------------------------------------------------------------------------------ // <copyright file="ICodeCompiler.cs" company="Microsoft"> // // <OWNER>petes</OWNER> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.CodeDom.Compiler { using System.Diagnostics; using System.IO; using System.Security.Permissions; /// <devdoc> /// <para> /// Provides a /// code compilation /// interface. /// </para> /// </devdoc> public interface ICodeCompiler { /// <devdoc> /// <para> /// Creates an assembly based on options, with the information from the compile units /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit); /// <devdoc> /// <para> /// Creates an assembly based on options, with the contents of /// fileName. /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName); /// <devdoc> /// <para> /// Creates an assembly based on options, with the information from /// source. /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source); /// <devdoc> /// <para> /// Compiles an assembly based on the specified options and /// information. /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits); /// <devdoc> /// <para> /// Compiles /// an /// assembly based on the specified options and contents of the specified /// filenames. /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames); /// <devdoc> /// <para> /// Compiles an assembly based on the specified options and information from the specified /// sources. /// </para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources); } }
mit
kangax/webgl-2d
test/philip.html5.org/tests/framed.2d.pattern.repeat.unrecognised.html
997
<!DOCTYPE html> <title>Canvas test: 2d.pattern.repeat.unrecognised</title> <script src="../tests.js"></script> <link rel="stylesheet" href="../tests.css"> <body class="framed show_output"> <h1> <a href="2d.pattern.repeat.unrecognised.html" target="_parent">2d.&#8203;pattern.&#8203;repeat.&#8203;unrecognised</a> </h1> <p><a href="#" id="show_output" onclick="document.body.className += ' show_output'; return false">[show output]</a> <p class="output">Actual output:</p> <canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> <ul id="d"></ul> <script> _addTest(function(canvas, ctx) { try { var _thrown = false; ctx.createPattern(canvas, "invalid"); } catch (e) { if (e.code != DOMException.SYNTAX_ERR) _fail("Failed assertion: expected exception of type SYNTAX_ERR, got: "+e.message); _thrown = true; } finally { _assert(_thrown, "should throw exception of type SYNTAX_ERR: ctx.createPattern(canvas, \"invalid\")"); } }); </script>
mit
vkadam/grunt-jsbeautifier
test/configFile_spec.js
3091
"use strict"; /*jshint -W079*/ var chai = require("chai"), expect = chai.expect, ncp = require('ncp').ncp, grunt = require("grunt"), JsBeautifierTask = require("../lib/jsbeautifier"), createMockTask = require("./mockTask"); chai.use(require('chai-fs')); /*jshint -W030*/ describe("JsBeautifier: Config file test", function() { var mockTask; beforeEach(function(done) { grunt.file.mkdir("tmp/configFile"); ncp("test/fixtures/configFile", "tmp/configFile", done); }); afterEach(function() { mockTask = null; grunt.file.delete("tmp"); }); function assertBeautifiedFile(actualFile, expectedFile) { var actual = "tmp/configFile/" + actualFile, expected = grunt.file.read("tmp/configFile/" + expectedFile); expect(actual).to.have.content(expected, "should beautify js " + actualFile + " using config file"); } it("beautification of js, css & html file using settings from config file", function(done) { var task; mockTask = createMockTask({ config: "tmp/configFile/jsbeautifyrc.json" }, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() { assertBeautifiedFile("test.js", "expected/test_expected.js"); assertBeautifiedFile("test.css", "expected/test_expected.css"); assertBeautifiedFile("test.html", "expected/test_expected.html"); done(); }); task = new JsBeautifierTask(mockTask); task.run(); }); it("beautification of js, css & html file using settings from flat config file", function(done) { var task; mockTask = createMockTask({ config: "tmp/configFile/jsbeautifyrc_flat.json" }, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() { assertBeautifiedFile("test.js", "expected/test_expected.js"); assertBeautifiedFile("test.css", "expected/test_expected.css"); assertBeautifiedFile("test.html", "expected/test_expected.html"); done(); }); task = new JsBeautifierTask(mockTask); task.run(); }); it("beautification of js, css & html file using settings from config file and gruntfile", function(done) { var task; mockTask = createMockTask({ config: "tmp/configFile/jsbeautifyrc_flat.json", css: { indentSize: 5 }, html: { indentSize: 7 } }, ["tmp/configFile/test.js", "tmp/configFile/test.css", "tmp/configFile/test.html"], function() { assertBeautifiedFile("test.js", "expected/withGruntFileOptions/test_expected.js"); assertBeautifiedFile("test.css", "expected/withGruntFileOptions/test_expected.css"); assertBeautifiedFile("test.html", "expected/withGruntFileOptions/test_expected.html"); done(); }); task = new JsBeautifierTask(mockTask); task.run(); }); });
mit
jigneshvasoya/fusekit
include/fusekit/tracer_buffer.h
1361
#ifndef __FUSEKIT__TRACER_BUFFER_H #define __FUSEKIT__TRACER_BUFFER_H #include <iostream> #include <fusekit/entry.h> namespace fusekit{ template< class Derived > struct tracer_buffer { tracer_buffer() : _os( std::cout ){ _os << "tracer_buffer::tracer_buffer()" << std::endl; } void set_ostream( std::ostream& os ) { _os = os; } ~tracer_buffer(){ _os << "tracer_buffer::~tracer_buffer()" << std::endl; } int open( fuse_file_info& ){ _os << "tracer_buffer::open(...)" << std::endl; return 0; } int close( fuse_file_info& ){ _os << "tracer_buffer::close(...)" << std::endl; return 0; } int size(){ _os << "tracer_buffer::size(...)" << std::endl; return 0; } int read( char* buf, size_t size, off_t offset, fuse_file_info& ){ _os << "tracer_buffer::read(...)" << std::endl; return 0; } int write( const char*, size_t, off_t, fuse_file_info& ){ _os << "tracer_buffer::write(...)" << std::endl; return 0; } int flush( fuse_file_info& ) { _os << "tracer_buffer::flush(...)" << std::endl; return 0; } int truncate( off_t offset ) { _os << "tracer_buffer::truncate(...)" << std::endl; return offset; } private: std::ostream&_os; }; } #endif
mit
askl56/rubyspec
library/net/ftp/mkdir_spec.rb
2358
require File.expand_path('../../../../spec_helper', __FILE__) require 'net/ftp' require File.expand_path('../fixtures/server', __FILE__) describe "Net::FTP#mkdir" do before :each do @server = NetFTPSpecs::DummyFTP.new @server.serve_once @ftp = Net::FTP.new @ftp.connect("localhost", 9921) end after :each do @ftp.quit rescue nil @ftp.close @server.stop end it "sends the MKD command with the passed pathname to the server" do @ftp.mkdir("test.folder") @ftp.last_response.should == %{257 "test.folder" created.\n} end it "returns the path to the newly created directory" do @ftp.mkdir("test.folder").should == "test.folder" @ftp.mkdir("/absolute/path/to/test.folder").should == "/absolute/path/to/test.folder" @ftp.mkdir("relative/path/to/test.folder").should == "relative/path/to/test.folder" @ftp.mkdir('/usr/dm/foo"bar').should == '/usr/dm/foo"bar' end it "raises a Net::FTPPermError when the response code is 500" do @server.should_receive(:mkd).and_respond("500 Syntax error, command unrecognized.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPPermError) end it "raises a Net::FTPPermError when the response code is 501" do @server.should_receive(:mkd).and_respond("501 Syntax error in parameters or arguments.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPPermError) end it "raises a Net::FTPPermError when the response code is 502" do @server.should_receive(:mkd).and_respond("502 Command not implemented.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPPermError) end it "raises a Net::FTPTempError when the response code is 421" do @server.should_receive(:mkd).and_respond("421 Service not available, closing control connection.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPTempError) end it "raises a Net::FTPPermError when the response code is 530" do @server.should_receive(:mkd).and_respond("530 Not logged in.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPPermError) end it "raises a Net::FTPPermError when the response code is 550" do @server.should_receive(:mkd).and_respond("550 Requested action not taken.") lambda { @ftp.mkdir("test.folder") }.should raise_error(Net::FTPPermError) end end
mit
olleolleolle/celluloid
lib/celluloid/test.rb
44
$CELLULOID_TEST = true require "celluloid"
mit
usetreno/KunstmaanBundlesCMS
src/Kunstmaan/SeoBundle/DependencyInjection/KunstmaanSeoExtension.php
914
<?php namespace Kunstmaan\SeoBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class KunstmaanSeoExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $loader->load('parameters.yml'); } }
mit
JeremyCraigMartinez/developer-dot
public/code/blog/avatax-connector-app/AvaTaxConnector/App_Start/BundleConfig.cs
2136
using System.Web; using System.Web.Optimization; namespace AvaTaxConnector { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css", "~/Content/themes/base/jquery.ui.selectable.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.autocomplete.css", "~/Content/themes/base/jquery.ui.button.css", "~/Content/themes/base/jquery.ui.dialog.css", "~/Content/themes/base/jquery.ui.slider.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); } } }
mit
r0zar/ember-rails-stocks
stocks/node_modules/ember-cli/lib/commands/test.js
6146
'use strict'; var Command = require('../models/command'); var Watcher = require('../models/watcher'); var Builder = require('../models/builder'); var SilentError = require('silent-error'); var path = require('path'); var win = require('../utilities/windows-admin'); var existsSync = require('exists-sync'); var defaultPort = 7357; module.exports = Command.extend({ name: 'test', description: 'Runs your app\'s test suite.', aliases: ['t'], availableOptions: [ { name: 'environment', type: String, default: 'test', aliases: ['e'] }, { name: 'config-file', type: String, aliases: ['c', 'cf']}, { name: 'server', type: Boolean, default: false, aliases: ['s'] }, { name: 'host', type: String, aliases: ['H'] }, { name: 'test-port', type: Number, default: defaultPort, aliases: ['tp'], description: 'The test port to use when running with --server.' }, { name: 'filter', type: String, aliases: ['f'], description: 'A string to filter tests to run' }, { name: 'module', type: String, aliases: ['m'], description: 'The name of a test module to run' }, { name: 'watcher', type: String, default: 'events', aliases: ['w'] }, { name: 'launch', type: String, default: false, description: 'A comma separated list of browsers to launch for tests.' }, { name: 'reporter', type: String, aliases: ['r'], description: 'Test reporter to use [tap|dot|xunit] (default: tap)' }, { name: 'silent', type: Boolean, default: false, description: 'Suppress any output except for the test report' }, { name: 'test-page', type: String, description: 'Test page to invoke' }, { name: 'path', type: 'Path', description: 'Reuse an existing build at given path.' }, { name: 'query', type: String, description: 'A query string to append to the test page URL.' } ], init: function() { this.assign = require('lodash/assign'); this.quickTemp = require('quick-temp'); this.Builder = this.Builder || Builder; this.Watcher = this.Watcher || Watcher; if (!this.testing) { process.env.EMBER_CLI_TEST_COMMAND = true; } }, tmp: function() { return this.quickTemp.makeOrRemake(this, '-testsDist'); }, rmTmp: function() { this.quickTemp.remove(this, '-testsDist'); this.quickTemp.remove(this, '-customConfigFile'); }, _generateCustomConfigs: function(options) { var config = {}; if (!options.filter && !options.module && !options.launch && !options.query && !options['test-page']) { return config; } var testPage = options['test-page']; var queryString = this.buildTestPageQueryString(options); if (testPage) { var containsQueryString = testPage.indexOf('?') > -1; var testPageJoinChar = containsQueryString ? '&' : '?'; config.testPage = testPage + testPageJoinChar + queryString; } if (queryString) { config.queryString = queryString; } if (options.launch) { config.launch = options.launch; } return config; }, _generateTestPortNumber: function(options) { if (options.port && options.testPort !== defaultPort || !isNaN(parseInt(options.testPort)) && !options.port) { return options.testPort; } if (options.port) { return parseInt(options.port, 10) + 1; } }, buildTestPageQueryString: function(options) { var params = []; if (options.module) { params.push('module=' + options.module); } if (options.filter) { params.push('filter=' + options.filter.toLowerCase()); } if (options.query) { params.push(options.query); } return params.join('&'); }, run: function(commandOptions) { var hasBuild = !!commandOptions.path; var outputPath; if (hasBuild) { outputPath = path.resolve(commandOptions.path); if (!existsSync(outputPath)) { throw new SilentError('The path ' + commandOptions.path + ' does not exist. Please specify a valid build directory to test.'); } } else { outputPath = this.tmp(); } process.env['EMBER_CLI_TEST_OUTPUT'] = outputPath; var testOptions = this.assign({}, commandOptions, { ui: this.ui, outputPath: outputPath, project: this.project, port: this._generateTestPortNumber(commandOptions) }, this._generateCustomConfigs(commandOptions)); var options = { ui: this.ui, analytics: this.analytics, project: this.project }; return win.checkWindowsElevation(this.ui).then(function() { var session; if (commandOptions.server) { if (hasBuild) { throw new SilentError('Specifying a build is not allowed with the `--server` option.'); } var TestServerTask = this.tasks.TestServer; var testServer = new TestServerTask(options); var builder = new this.Builder(testOptions); testOptions.watcher = new this.Watcher(this.assign(options, { builder: builder, verbose: false, options: commandOptions })); session = testServer.run(testOptions).finally(function() { return builder.cleanup(); }); } else { var TestTask = this.tasks.Test; var test = new TestTask(options); if (hasBuild) { session = test.run(testOptions); } else { var BuildTask = this.tasks.Build; var build = new BuildTask(options); session = build.run({ environment: commandOptions.environment, outputPath: outputPath }) .then(function() { return test.run(testOptions); }) } } return session.finally(this.rmTmp.bind(this)); }.bind(this)); } });
mit
GNOME/banshee
src/Backends/Banshee.Osx/Banshee.Hardware.Osx/DiscVolume.cs
2171
// // DiscVolume.cs // // Author: // Timo Dörr <[email protected]> // // Copyright 2012 Timo Dörr // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoMac.Foundation; using Banshee.Hardware.Osx.LowLevel; namespace Banshee.Hardware.Osx { public class DiscVolume : Volume, IDiscVolume { public DiscVolume (DeviceArguments arguments, IBlockDevice b) : base(arguments, b) { } #region IDiscVolume implementation public bool HasAudio { get { return true; } } public bool HasData { get { return false; } } public bool HasVideo { get { return false; } } public bool IsRewritable { get { return false; } } public bool IsBlank { get { return false; } } public ulong MediaCapacity { get { return 128338384858; } } #endregion } }
mit
impedimentToProgress/UCI-BlueChip
snapgear_linux/linux-2.6.21.1/fs/compat_ioctl.c
73919
/* * ioctl32.c: Conversion between 32bit and 64bit native ioctls. * * Copyright (C) 1997-2000 Jakub Jelinek ([email protected]) * Copyright (C) 1998 Eddie C. Dost ([email protected]) * Copyright (C) 2001,2002 Andi Kleen, SuSE Labs * Copyright (C) 2003 Pavel Machek ([email protected]) * * These routines maintain argument size conversion between 32bit and 64bit * ioctls. */ #include <linux/types.h> #include <linux/compat.h> #include <linux/kernel.h> #include <linux/capability.h> #include <linux/compiler.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/smp_lock.h> #include <linux/ioctl.h> #include <linux/if.h> #include <linux/if_bridge.h> #include <linux/slab.h> #include <linux/hdreg.h> #include <linux/raid/md.h> #include <linux/kd.h> #include <linux/dirent.h> #include <linux/route.h> #include <linux/in6.h> #include <linux/ipv6_route.h> #include <linux/skbuff.h> #include <linux/netlink.h> #include <linux/vt.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/fd.h> #include <linux/ppp_defs.h> #include <linux/if_ppp.h> #include <linux/if_pppox.h> #include <linux/mtio.h> #include <linux/cdrom.h> #include <linux/auto_fs.h> #include <linux/auto_fs4.h> #include <linux/tty.h> #include <linux/vt_kern.h> #include <linux/fb.h> #include <linux/videodev.h> #include <linux/netdevice.h> #include <linux/raw.h> #include <linux/smb_fs.h> #include <linux/blkpg.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <linux/rtc.h> #include <linux/pci.h> #include <linux/module.h> #include <linux/serial.h> #include <linux/if_tun.h> #include <linux/ctype.h> #include <linux/ioctl32.h> #include <linux/syscalls.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <linux/wireless.h> #include <linux/atalk.h> #include <linux/blktrace_api.h> #include <net/sock.h> /* siocdevprivate_ioctl */ #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci.h> #include <net/bluetooth/rfcomm.h> #include <linux/capi.h> #include <linux/gigaset_dev.h> #include <scsi/scsi.h> #include <scsi/scsi_ioctl.h> #include <scsi/sg.h> #include <asm/uaccess.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/if_bonding.h> #include <linux/watchdog.h> #include <linux/dm-ioctl.h> #include <linux/soundcard.h> #include <linux/lp.h> #include <linux/ppdev.h> #include <linux/atm.h> #include <linux/atmarp.h> #include <linux/atmclip.h> #include <linux/atmdev.h> #include <linux/atmioc.h> #include <linux/atmlec.h> #include <linux/atmmpc.h> #include <linux/atmsvc.h> #include <linux/atm_tcp.h> #include <linux/sonet.h> #include <linux/atm_suni.h> #include <linux/mtd/mtd.h> #include <linux/usb.h> #include <linux/usbdevice_fs.h> #include <linux/nbd.h> #include <linux/random.h> #include <linux/filter.h> #include <linux/pktcdvd.h> #include <linux/hiddev.h> #include <linux/dvb/audio.h> #include <linux/dvb/dmx.h> #include <linux/dvb/frontend.h> #include <linux/dvb/video.h> #include <linux/lp.h> static int do_ioctl32_pointer(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *f) { return sys_ioctl(fd, cmd, (unsigned long)compat_ptr(arg)); } static int w_long(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); int err; unsigned long val; set_fs (KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long)&val); set_fs (old_fs); if (!err && put_user(val, (u32 __user *)compat_ptr(arg))) return -EFAULT; return err; } static int rw_long(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); u32 __user *argptr = compat_ptr(arg); int err; unsigned long val; if(get_user(val, argptr)) return -EFAULT; set_fs (KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long)&val); set_fs (old_fs); if (!err && put_user(val, argptr)) return -EFAULT; return err; } struct compat_video_event { int32_t type; compat_time_t timestamp; union { video_size_t size; unsigned int frame_rate; } u; }; static int do_video_get_event(unsigned int fd, unsigned int cmd, unsigned long arg) { struct video_event kevent; mm_segment_t old_fs = get_fs(); int err; set_fs(KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long) &kevent); set_fs(old_fs); if (!err) { struct compat_video_event __user *up = compat_ptr(arg); err = put_user(kevent.type, &up->type); err |= put_user(kevent.timestamp, &up->timestamp); err |= put_user(kevent.u.size.w, &up->u.size.w); err |= put_user(kevent.u.size.h, &up->u.size.h); err |= put_user(kevent.u.size.aspect_ratio, &up->u.size.aspect_ratio); if (err) err = -EFAULT; } return err; } struct compat_video_still_picture { compat_uptr_t iFrame; int32_t size; }; static int do_video_stillpicture(unsigned int fd, unsigned int cmd, unsigned long arg) { struct compat_video_still_picture __user *up; struct video_still_picture __user *up_native; compat_uptr_t fp; int32_t size; int err; up = (struct compat_video_still_picture __user *) arg; err = get_user(fp, &up->iFrame); err |= get_user(size, &up->size); if (err) return -EFAULT; up_native = compat_alloc_user_space(sizeof(struct video_still_picture)); err = put_user(compat_ptr(fp), &up_native->iFrame); err |= put_user(size, &up_native->size); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } struct compat_video_spu_palette { int length; compat_uptr_t palette; }; static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd, unsigned long arg) { struct compat_video_spu_palette __user *up; struct video_spu_palette __user *up_native; compat_uptr_t palp; int length, err; up = (struct compat_video_spu_palette __user *) arg; err = get_user(palp, &up->palette); err |= get_user(length, &up->length); up_native = compat_alloc_user_space(sizeof(struct video_spu_palette)); err = put_user(compat_ptr(palp), &up_native->palette); err |= put_user(length, &up_native->length); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } #ifdef CONFIG_NET static int do_siocgstamp(unsigned int fd, unsigned int cmd, unsigned long arg) { struct compat_timeval __user *up = compat_ptr(arg); struct timeval ktv; mm_segment_t old_fs = get_fs(); int err; set_fs(KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long)&ktv); set_fs(old_fs); if(!err) { err = put_user(ktv.tv_sec, &up->tv_sec); err |= __put_user(ktv.tv_usec, &up->tv_usec); } return err; } struct ifmap32 { compat_ulong_t mem_start; compat_ulong_t mem_end; unsigned short base_addr; unsigned char irq; unsigned char dma; unsigned char port; }; struct ifreq32 { #define IFHWADDRLEN 6 #define IFNAMSIZ 16 union { char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */ } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; compat_int_t ifru_ivalue; compat_int_t ifru_mtu; struct ifmap32 ifru_map; char ifru_slave[IFNAMSIZ]; /* Just fits the size */ char ifru_newname[IFNAMSIZ]; compat_caddr_t ifru_data; /* XXXX? ifru_settings should be here */ } ifr_ifru; }; struct ifconf32 { compat_int_t ifc_len; /* size of buffer */ compat_caddr_t ifcbuf; }; static int dev_ifname32(unsigned int fd, unsigned int cmd, unsigned long arg) { struct net_device *dev; struct ifreq32 ifr32; int err; if (copy_from_user(&ifr32, compat_ptr(arg), sizeof(ifr32))) return -EFAULT; dev = dev_get_by_index(ifr32.ifr_ifindex); if (!dev) return -ENODEV; strlcpy(ifr32.ifr_name, dev->name, sizeof(ifr32.ifr_name)); dev_put(dev); err = copy_to_user(compat_ptr(arg), &ifr32, sizeof(ifr32)); return (err ? -EFAULT : 0); } static int dev_ifconf(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ifconf32 ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct ifreq32 __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, compat_ptr(arg), sizeof(struct ifconf32))) return -EFAULT; if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len =((ifc32.ifc_len / sizeof (struct ifreq32)) + 1) * sizeof (struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof (struct ifreq32)) { if (copy_in_user(ifr, ifr32, sizeof(struct ifreq32))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = sys_ioctl (fd, SIOCGIFCONF, (unsigned long)uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof (struct ifreq32) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof (struct ifreq32), j += sizeof (struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof (struct ifreq32))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct ifreq32)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(compat_ptr(arg), &ifc32, sizeof(struct ifconf32))) return -EFAULT; return 0; } static int ethtool_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ifreq __user *ifr; struct ifreq32 __user *ifr32; u32 data; void __user *datap; ifr = compat_alloc_user_space(sizeof(*ifr)); ifr32 = compat_ptr(arg); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &ifr->ifr_ifru.ifru_data)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long) ifr); } static int bond_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ifreq kifr; struct ifreq __user *uifr; struct ifreq32 __user *ifr32 = compat_ptr(arg); mm_segment_t old_fs; int err; u32 data; void __user *datap; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct ifreq32))) return -EFAULT; old_fs = get_fs(); set_fs (KERNEL_DS); err = sys_ioctl (fd, cmd, (unsigned long)&kifr); set_fs (old_fs); return err; case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(&uifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &uifr->ifr_ifru.ifru_data)) return -EFAULT; return sys_ioctl (fd, cmd, (unsigned long)uifr); default: return -EINVAL; }; } int siocdevprivate_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ifreq __user *u_ifreq64; struct ifreq32 __user *u_ifreq32 = compat_ptr(arg); char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (__get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); /* Don't check these user accesses, just let that get trapped * in the ioctl handler instead. */ if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (__put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long) u_ifreq64); } static int dev_ifsioc(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ifreq ifr; struct ifreq32 __user *uifr32; struct ifmap32 __user *uifmap32; mm_segment_t old_fs; int err; uifr32 = compat_ptr(arg); uifmap32 = &uifr32->ifr_ifru.ifru_map; switch (cmd) { case SIOCSIFMAP: err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= __get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; break; default: if (copy_from_user(&ifr, uifr32, sizeof(*uifr32))) return -EFAULT; break; } old_fs = get_fs(); set_fs (KERNEL_DS); err = sys_ioctl (fd, cmd, (unsigned long)&ifr); set_fs (old_fs); if (!err) { switch (cmd) { /* TUNSETIFF is defined as _IOW, it should be _IORW * as the data is copied back to user space, but that * cannot be fixed without breaking all existing apps. */ case TUNSETIFF: case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFTXQLEN: if (copy_to_user(uifr32, &ifr, sizeof(*uifr32))) return -EFAULT; break; case SIOCGIFMAP: err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= __put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; break; } } return err; } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); struct socket *mysock = sockfd_lookup(fd, &ret); if (mysock && mysock->sk && mysock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = compat_ptr(arg); ret = copy_from_user (&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= __get_user (r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= __get_user (r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= __get_user (r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= __get_user (r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= __get_user (r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= __get_user (r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= __get_user (r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = compat_ptr(arg); ret = copy_from_user (&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= __get_user (r4.rt_flags, &(ur4->rt_flags)); ret |= __get_user (r4.rt_metric, &(ur4->rt_metric)); ret |= __get_user (r4.rt_mtu, &(ur4->rt_mtu)); ret |= __get_user (r4.rt_window, &(ur4->rt_window)); ret |= __get_user (r4.rt_irtt, &(ur4->rt_irtt)); ret |= __get_user (rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user (devname, compat_ptr(rtdev), 15); r4.rt_dev = devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs (KERNEL_DS); ret = sys_ioctl (fd, cmd, (unsigned long) r); set_fs (old_fs); out: if (mysock) sockfd_put(mysock); return ret; } #endif #ifdef CONFIG_BLOCK struct hd_geometry32 { unsigned char heads; unsigned char sectors; unsigned short cylinders; u32 start; }; static int hdio_getgeo(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); struct hd_geometry geo; struct hd_geometry32 __user *ugeo; int err; set_fs (KERNEL_DS); err = sys_ioctl(fd, HDIO_GETGEO, (unsigned long)&geo); set_fs (old_fs); ugeo = compat_ptr(arg); if (!err) { err = copy_to_user (ugeo, &geo, 4); err |= __put_user (geo.start, &ugeo->start); } return err ? -EFAULT : 0; } static int hdio_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); unsigned long kval; unsigned int __user *uvp; int error; set_fs(KERNEL_DS); error = sys_ioctl(fd, cmd, (long)&kval); set_fs(old_fs); if(error == 0) { uvp = compat_ptr(arg); if(put_user(kval, uvp)) error = -EFAULT; } return error; } typedef struct sg_io_hdr32 { compat_int_t interface_id; /* [i] 'S' for SCSI generic (required) */ compat_int_t dxfer_direction; /* [i] data transfer direction */ unsigned char cmd_len; /* [i] SCSI command length ( <= 16 bytes) */ unsigned char mx_sb_len; /* [i] max length to write to sbp */ unsigned short iovec_count; /* [i] 0 implies no scatter gather */ compat_uint_t dxfer_len; /* [i] byte count of data transfer */ compat_uint_t dxferp; /* [i], [*io] points to data transfer memory or scatter gather list */ compat_uptr_t cmdp; /* [i], [*i] points to command to perform */ compat_uptr_t sbp; /* [i], [*o] points to sense_buffer memory */ compat_uint_t timeout; /* [i] MAX_UINT->no timeout (unit: millisec) */ compat_uint_t flags; /* [i] 0 -> default, see SG_FLAG... */ compat_int_t pack_id; /* [i->o] unused internally (normally) */ compat_uptr_t usr_ptr; /* [i->o] unused internally */ unsigned char status; /* [o] scsi status */ unsigned char masked_status; /* [o] shifted, masked scsi status */ unsigned char msg_status; /* [o] messaging level data (optional) */ unsigned char sb_len_wr; /* [o] byte count actually written to sbp */ unsigned short host_status; /* [o] errors from host adapter */ unsigned short driver_status; /* [o] errors from software driver */ compat_int_t resid; /* [o] dxfer_len - actual_transferred */ compat_uint_t duration; /* [o] time taken by cmd (unit: millisec) */ compat_uint_t info; /* [o] auxiliary information */ } sg_io_hdr32_t; /* 64 bytes long (on sparc32) */ typedef struct sg_iovec32 { compat_uint_t iov_base; compat_uint_t iov_len; } sg_iovec32_t; static int sg_build_iovec(sg_io_hdr_t __user *sgio, void __user *dxferp, u16 iovec_count) { sg_iovec_t __user *iov = (sg_iovec_t __user *) (sgio + 1); sg_iovec32_t __user *iov32 = dxferp; int i; for (i = 0; i < iovec_count; i++) { u32 base, len; if (get_user(base, &iov32[i].iov_base) || get_user(len, &iov32[i].iov_len) || put_user(compat_ptr(base), &iov[i].iov_base) || put_user(len, &iov[i].iov_len)) return -EFAULT; } if (put_user(iov, &sgio->dxferp)) return -EFAULT; return 0; } static int sg_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { sg_io_hdr_t __user *sgio; sg_io_hdr32_t __user *sgio32; u16 iovec_count; u32 data; void __user *dxferp; int err; sgio32 = compat_ptr(arg); if (get_user(iovec_count, &sgio32->iovec_count)) return -EFAULT; { void __user *top = compat_alloc_user_space(0); void __user *new = compat_alloc_user_space(sizeof(sg_io_hdr_t) + (iovec_count * sizeof(sg_iovec_t))); if (new > top) return -EINVAL; sgio = new; } /* Ok, now construct. */ if (copy_in_user(&sgio->interface_id, &sgio32->interface_id, (2 * sizeof(int)) + (2 * sizeof(unsigned char)) + (1 * sizeof(unsigned short)) + (1 * sizeof(unsigned int)))) return -EFAULT; if (get_user(data, &sgio32->dxferp)) return -EFAULT; dxferp = compat_ptr(data); if (iovec_count) { if (sg_build_iovec(sgio, dxferp, iovec_count)) return -EFAULT; } else { if (put_user(dxferp, &sgio->dxferp)) return -EFAULT; } { unsigned char __user *cmdp; unsigned char __user *sbp; if (get_user(data, &sgio32->cmdp)) return -EFAULT; cmdp = compat_ptr(data); if (get_user(data, &sgio32->sbp)) return -EFAULT; sbp = compat_ptr(data); if (put_user(cmdp, &sgio->cmdp) || put_user(sbp, &sgio->sbp)) return -EFAULT; } if (copy_in_user(&sgio->timeout, &sgio32->timeout, 3 * sizeof(int))) return -EFAULT; if (get_user(data, &sgio32->usr_ptr)) return -EFAULT; if (put_user(compat_ptr(data), &sgio->usr_ptr)) return -EFAULT; if (copy_in_user(&sgio->status, &sgio32->status, (4 * sizeof(unsigned char)) + (2 * sizeof(unsigned (short))) + (3 * sizeof(int)))) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) sgio); if (err >= 0) { void __user *datap; if (copy_in_user(&sgio32->pack_id, &sgio->pack_id, sizeof(int)) || get_user(datap, &sgio->usr_ptr) || put_user((u32)(unsigned long)datap, &sgio32->usr_ptr) || copy_in_user(&sgio32->status, &sgio->status, (4 * sizeof(unsigned char)) + (2 * sizeof(unsigned short)) + (3 * sizeof(int)))) err = -EFAULT; } return err; } struct compat_sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */ char req_state; char orphan; char sg_io_owned; char problem; int pack_id; compat_uptr_t usr_ptr; unsigned int duration; int unused; }; static int sg_grt_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { int err, i; sg_req_info_t __user *r; struct compat_sg_req_info __user *o = (void __user *)arg; r = compat_alloc_user_space(sizeof(sg_req_info_t)*SG_MAX_QUEUE); err = sys_ioctl(fd,cmd,(unsigned long)r); if (err < 0) return err; for (i = 0; i < SG_MAX_QUEUE; i++) { void __user *ptr; int d; if (copy_in_user(o + i, r + i, offsetof(sg_req_info_t, usr_ptr)) || get_user(ptr, &r[i].usr_ptr) || get_user(d, &r[i].duration) || put_user((u32)(unsigned long)(ptr), &o[i].usr_ptr) || put_user(d, &o[i].duration)) return -EFAULT; } return err; } #endif /* CONFIG_BLOCK */ struct sock_fprog32 { unsigned short len; compat_caddr_t filter; }; #define PPPIOCSPASS32 _IOW('t', 71, struct sock_fprog32) #define PPPIOCSACTIVE32 _IOW('t', 70, struct sock_fprog32) static int ppp_sock_fprog_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { struct sock_fprog32 __user *u_fprog32 = compat_ptr(arg); struct sock_fprog __user *u_fprog64 = compat_alloc_user_space(sizeof(struct sock_fprog)); void __user *fptr64; u32 fptr32; u16 flen; if (get_user(flen, &u_fprog32->len) || get_user(fptr32, &u_fprog32->filter)) return -EFAULT; fptr64 = compat_ptr(fptr32); if (put_user(flen, &u_fprog64->len) || put_user(fptr64, &u_fprog64->filter)) return -EFAULT; if (cmd == PPPIOCSPASS32) cmd = PPPIOCSPASS; else cmd = PPPIOCSACTIVE; return sys_ioctl(fd, cmd, (unsigned long) u_fprog64); } struct ppp_option_data32 { compat_caddr_t ptr; u32 length; compat_int_t transmit; }; #define PPPIOCSCOMPRESS32 _IOW('t', 77, struct ppp_option_data32) struct ppp_idle32 { compat_time_t xmit_idle; compat_time_t recv_idle; }; #define PPPIOCGIDLE32 _IOR('t', 63, struct ppp_idle32) static int ppp_gidle(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ppp_idle __user *idle; struct ppp_idle32 __user *idle32; __kernel_time_t xmit, recv; int err; idle = compat_alloc_user_space(sizeof(*idle)); idle32 = compat_ptr(arg); err = sys_ioctl(fd, PPPIOCGIDLE, (unsigned long) idle); if (!err) { if (get_user(xmit, &idle->xmit_idle) || get_user(recv, &idle->recv_idle) || put_user(xmit, &idle32->xmit_idle) || put_user(recv, &idle32->recv_idle)) err = -EFAULT; } return err; } static int ppp_scompress(unsigned int fd, unsigned int cmd, unsigned long arg) { struct ppp_option_data __user *odata; struct ppp_option_data32 __user *odata32; __u32 data; void __user *datap; odata = compat_alloc_user_space(sizeof(*odata)); odata32 = compat_ptr(arg); if (get_user(data, &odata32->ptr)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &odata->ptr)) return -EFAULT; if (copy_in_user(&odata->length, &odata32->length, sizeof(__u32) + sizeof(int))) return -EFAULT; return sys_ioctl(fd, PPPIOCSCOMPRESS, (unsigned long) odata); } static int ppp_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { int err; switch (cmd) { case PPPIOCGIDLE32: err = ppp_gidle(fd, cmd, arg); break; case PPPIOCSCOMPRESS32: err = ppp_scompress(fd, cmd, arg); break; default: do { static int count; if (++count <= 20) printk("ppp_ioctl: Unknown cmd fd(%d) " "cmd(%08x) arg(%08x)\n", (int)fd, (unsigned int)cmd, (unsigned int)arg); } while(0); err = -EINVAL; break; }; return err; } #ifdef CONFIG_BLOCK struct mtget32 { compat_long_t mt_type; compat_long_t mt_resid; compat_long_t mt_dsreg; compat_long_t mt_gstat; compat_long_t mt_erreg; compat_daddr_t mt_fileno; compat_daddr_t mt_blkno; }; #define MTIOCGET32 _IOR('m', 2, struct mtget32) struct mtpos32 { compat_long_t mt_blkno; }; #define MTIOCPOS32 _IOR('m', 3, struct mtpos32) static int mt_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); struct mtget get; struct mtget32 __user *umget32; struct mtpos pos; struct mtpos32 __user *upos32; unsigned long kcmd; void *karg; int err = 0; switch(cmd) { case MTIOCPOS32: kcmd = MTIOCPOS; karg = &pos; break; case MTIOCGET32: kcmd = MTIOCGET; karg = &get; break; default: do { static int count; if (++count <= 20) printk("mt_ioctl: Unknown cmd fd(%d) " "cmd(%08x) arg(%08x)\n", (int)fd, (unsigned int)cmd, (unsigned int)arg); } while(0); return -EINVAL; } set_fs (KERNEL_DS); err = sys_ioctl (fd, kcmd, (unsigned long)karg); set_fs (old_fs); if (err) return err; switch (cmd) { case MTIOCPOS32: upos32 = compat_ptr(arg); err = __put_user(pos.mt_blkno, &upos32->mt_blkno); break; case MTIOCGET32: umget32 = compat_ptr(arg); err = __put_user(get.mt_type, &umget32->mt_type); err |= __put_user(get.mt_resid, &umget32->mt_resid); err |= __put_user(get.mt_dsreg, &umget32->mt_dsreg); err |= __put_user(get.mt_gstat, &umget32->mt_gstat); err |= __put_user(get.mt_erreg, &umget32->mt_erreg); err |= __put_user(get.mt_fileno, &umget32->mt_fileno); err |= __put_user(get.mt_blkno, &umget32->mt_blkno); break; } return err ? -EFAULT: 0; } struct cdrom_read_audio32 { union cdrom_addr addr; u8 addr_format; compat_int_t nframes; compat_caddr_t buf; }; struct cdrom_generic_command32 { unsigned char cmd[CDROM_PACKET_SIZE]; compat_caddr_t buffer; compat_uint_t buflen; compat_int_t stat; compat_caddr_t sense; unsigned char data_direction; compat_int_t quiet; compat_int_t timeout; compat_caddr_t reserved[1]; }; static int cdrom_do_read_audio(unsigned int fd, unsigned int cmd, unsigned long arg) { struct cdrom_read_audio __user *cdread_audio; struct cdrom_read_audio32 __user *cdread_audio32; __u32 data; void __user *datap; cdread_audio = compat_alloc_user_space(sizeof(*cdread_audio)); cdread_audio32 = compat_ptr(arg); if (copy_in_user(&cdread_audio->addr, &cdread_audio32->addr, (sizeof(*cdread_audio32) - sizeof(compat_caddr_t)))) return -EFAULT; if (get_user(data, &cdread_audio32->buf)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &cdread_audio->buf)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long) cdread_audio); } static int cdrom_do_generic_command(unsigned int fd, unsigned int cmd, unsigned long arg) { struct cdrom_generic_command __user *cgc; struct cdrom_generic_command32 __user *cgc32; u32 data; unsigned char dir; int itmp; cgc = compat_alloc_user_space(sizeof(*cgc)); cgc32 = compat_ptr(arg); if (copy_in_user(&cgc->cmd, &cgc32->cmd, sizeof(cgc->cmd)) || get_user(data, &cgc32->buffer) || put_user(compat_ptr(data), &cgc->buffer) || copy_in_user(&cgc->buflen, &cgc32->buflen, (sizeof(unsigned int) + sizeof(int))) || get_user(data, &cgc32->sense) || put_user(compat_ptr(data), &cgc->sense) || get_user(dir, &cgc32->data_direction) || put_user(dir, &cgc->data_direction) || get_user(itmp, &cgc32->quiet) || put_user(itmp, &cgc->quiet) || get_user(itmp, &cgc32->timeout) || put_user(itmp, &cgc->timeout) || get_user(data, &cgc32->reserved[0]) || put_user(compat_ptr(data), &cgc->reserved[0])) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long) cgc); } static int cdrom_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { int err; switch(cmd) { case CDROMREADAUDIO: err = cdrom_do_read_audio(fd, cmd, arg); break; case CDROM_SEND_PACKET: err = cdrom_do_generic_command(fd, cmd, arg); break; default: do { static int count; if (++count <= 20) printk("cdrom_ioctl: Unknown cmd fd(%d) " "cmd(%08x) arg(%08x)\n", (int)fd, (unsigned int)cmd, (unsigned int)arg); } while(0); err = -EINVAL; break; }; return err; } #endif /* CONFIG_BLOCK */ #ifdef CONFIG_VT static int vt_check(struct file *file) { struct tty_struct *tty; struct inode *inode = file->f_path.dentry->d_inode; if (file->f_op->ioctl != tty_ioctl) return -EINVAL; tty = (struct tty_struct *)file->private_data; if (tty_paranoia_check(tty, inode, "tty_ioctl")) return -EINVAL; if (tty->driver->ioctl != vt_ioctl) return -EINVAL; /* * To have permissions to do most of the vt ioctls, we either have * to be the owner of the tty, or super-user. */ if (current->signal->tty == tty || capable(CAP_SYS_ADMIN)) return 1; return 0; } struct consolefontdesc32 { unsigned short charcount; /* characters in font (256 or 512) */ unsigned short charheight; /* scan lines per character (1-32) */ compat_caddr_t chardata; /* font data in expanded form */ }; static int do_fontx_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *file) { struct consolefontdesc32 __user *user_cfd = compat_ptr(arg); struct console_font_op op; compat_caddr_t data; int i, perm; perm = vt_check(file); if (perm < 0) return perm; switch (cmd) { case PIO_FONTX: if (!perm) return -EPERM; op.op = KD_FONT_OP_SET; op.flags = 0; op.width = 8; if (get_user(op.height, &user_cfd->charheight) || get_user(op.charcount, &user_cfd->charcount) || get_user(data, &user_cfd->chardata)) return -EFAULT; op.data = compat_ptr(data); return con_font_op(vc_cons[fg_console].d, &op); case GIO_FONTX: op.op = KD_FONT_OP_GET; op.flags = 0; op.width = 8; if (get_user(op.height, &user_cfd->charheight) || get_user(op.charcount, &user_cfd->charcount) || get_user(data, &user_cfd->chardata)) return -EFAULT; if (!data) return 0; op.data = compat_ptr(data); i = con_font_op(vc_cons[fg_console].d, &op); if (i) return i; if (put_user(op.height, &user_cfd->charheight) || put_user(op.charcount, &user_cfd->charcount) || put_user((compat_caddr_t)(unsigned long)op.data, &user_cfd->chardata)) return -EFAULT; return 0; } return -EINVAL; } struct console_font_op32 { compat_uint_t op; /* operation code KD_FONT_OP_* */ compat_uint_t flags; /* KD_FONT_FLAG_* */ compat_uint_t width, height; /* font size */ compat_uint_t charcount; compat_caddr_t data; /* font data with height fixed to 32 */ }; static int do_kdfontop_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *file) { struct console_font_op op; struct console_font_op32 __user *fontop = compat_ptr(arg); int perm = vt_check(file), i; struct vc_data *vc; if (perm < 0) return perm; if (copy_from_user(&op, fontop, sizeof(struct console_font_op32))) return -EFAULT; if (!perm && op.op != KD_FONT_OP_GET) return -EPERM; op.data = compat_ptr(((struct console_font_op32 *)&op)->data); op.flags |= KD_FONT_FLAG_OLD; vc = ((struct tty_struct *)file->private_data)->driver_data; i = con_font_op(vc, &op); if (i) return i; ((struct console_font_op32 *)&op)->data = (unsigned long)op.data; if (copy_to_user(fontop, &op, sizeof(struct console_font_op32))) return -EFAULT; return 0; } struct unimapdesc32 { unsigned short entry_ct; compat_caddr_t entries; }; static int do_unimap_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *file) { struct unimapdesc32 tmp; struct unimapdesc32 __user *user_ud = compat_ptr(arg); int perm = vt_check(file); if (perm < 0) return perm; if (copy_from_user(&tmp, user_ud, sizeof tmp)) return -EFAULT; switch (cmd) { case PIO_UNIMAP: if (!perm) return -EPERM; return con_set_unimap(vc_cons[fg_console].d, tmp.entry_ct, compat_ptr(tmp.entries)); case GIO_UNIMAP: return con_get_unimap(vc_cons[fg_console].d, tmp.entry_ct, &(user_ud->entry_ct), compat_ptr(tmp.entries)); } return 0; } #endif /* CONFIG_VT */ static int do_smb_getmountuid(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); __kernel_uid_t kuid; int err; cmd = SMB_IOC_GETMOUNTUID; set_fs(KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long)&kuid); set_fs(old_fs); if (err >= 0) err = put_user(kuid, (compat_uid_t __user *)compat_ptr(arg)); return err; } struct atmif_sioc32 { compat_int_t number; compat_int_t length; compat_caddr_t arg; }; struct atm_iobuf32 { compat_int_t length; compat_caddr_t buffer; }; #define ATM_GETLINKRATE32 _IOW('a', ATMIOC_ITF+1, struct atmif_sioc32) #define ATM_GETNAMES32 _IOW('a', ATMIOC_ITF+3, struct atm_iobuf32) #define ATM_GETTYPE32 _IOW('a', ATMIOC_ITF+4, struct atmif_sioc32) #define ATM_GETESI32 _IOW('a', ATMIOC_ITF+5, struct atmif_sioc32) #define ATM_GETADDR32 _IOW('a', ATMIOC_ITF+6, struct atmif_sioc32) #define ATM_RSTADDR32 _IOW('a', ATMIOC_ITF+7, struct atmif_sioc32) #define ATM_ADDADDR32 _IOW('a', ATMIOC_ITF+8, struct atmif_sioc32) #define ATM_DELADDR32 _IOW('a', ATMIOC_ITF+9, struct atmif_sioc32) #define ATM_GETCIRANGE32 _IOW('a', ATMIOC_ITF+10, struct atmif_sioc32) #define ATM_SETCIRANGE32 _IOW('a', ATMIOC_ITF+11, struct atmif_sioc32) #define ATM_SETESI32 _IOW('a', ATMIOC_ITF+12, struct atmif_sioc32) #define ATM_SETESIF32 _IOW('a', ATMIOC_ITF+13, struct atmif_sioc32) #define ATM_GETSTAT32 _IOW('a', ATMIOC_SARCOM+0, struct atmif_sioc32) #define ATM_GETSTATZ32 _IOW('a', ATMIOC_SARCOM+1, struct atmif_sioc32) #define ATM_GETLOOP32 _IOW('a', ATMIOC_SARCOM+2, struct atmif_sioc32) #define ATM_SETLOOP32 _IOW('a', ATMIOC_SARCOM+3, struct atmif_sioc32) #define ATM_QUERYLOOP32 _IOW('a', ATMIOC_SARCOM+4, struct atmif_sioc32) static struct { unsigned int cmd32; unsigned int cmd; } atm_ioctl_map[] = { { ATM_GETLINKRATE32, ATM_GETLINKRATE }, { ATM_GETNAMES32, ATM_GETNAMES }, { ATM_GETTYPE32, ATM_GETTYPE }, { ATM_GETESI32, ATM_GETESI }, { ATM_GETADDR32, ATM_GETADDR }, { ATM_RSTADDR32, ATM_RSTADDR }, { ATM_ADDADDR32, ATM_ADDADDR }, { ATM_DELADDR32, ATM_DELADDR }, { ATM_GETCIRANGE32, ATM_GETCIRANGE }, { ATM_SETCIRANGE32, ATM_SETCIRANGE }, { ATM_SETESI32, ATM_SETESI }, { ATM_SETESIF32, ATM_SETESIF }, { ATM_GETSTAT32, ATM_GETSTAT }, { ATM_GETSTATZ32, ATM_GETSTATZ }, { ATM_GETLOOP32, ATM_GETLOOP }, { ATM_SETLOOP32, ATM_SETLOOP }, { ATM_QUERYLOOP32, ATM_QUERYLOOP } }; #define NR_ATM_IOCTL ARRAY_SIZE(atm_ioctl_map) static int do_atm_iobuf(unsigned int fd, unsigned int cmd, unsigned long arg) { struct atm_iobuf __user *iobuf; struct atm_iobuf32 __user *iobuf32; u32 data; void __user *datap; int len, err; iobuf = compat_alloc_user_space(sizeof(*iobuf)); iobuf32 = compat_ptr(arg); if (get_user(len, &iobuf32->length) || get_user(data, &iobuf32->buffer)) return -EFAULT; datap = compat_ptr(data); if (put_user(len, &iobuf->length) || put_user(datap, &iobuf->buffer)) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long)iobuf); if (!err) { if (copy_in_user(&iobuf32->length, &iobuf->length, sizeof(int))) err = -EFAULT; } return err; } static int do_atmif_sioc(unsigned int fd, unsigned int cmd, unsigned long arg) { struct atmif_sioc __user *sioc; struct atmif_sioc32 __user *sioc32; u32 data; void __user *datap; int err; sioc = compat_alloc_user_space(sizeof(*sioc)); sioc32 = compat_ptr(arg); if (copy_in_user(&sioc->number, &sioc32->number, 2 * sizeof(int)) || get_user(data, &sioc32->arg)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &sioc->arg)) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) sioc); if (!err) { if (copy_in_user(&sioc32->length, &sioc->length, sizeof(int))) err = -EFAULT; } return err; } static int do_atm_ioctl(unsigned int fd, unsigned int cmd32, unsigned long arg) { int i; unsigned int cmd = 0; switch (cmd32) { case SONET_GETSTAT: case SONET_GETSTATZ: case SONET_GETDIAG: case SONET_SETDIAG: case SONET_CLRDIAG: case SONET_SETFRAMING: case SONET_GETFRAMING: case SONET_GETFRSENSE: return do_atmif_sioc(fd, cmd32, arg); } for (i = 0; i < NR_ATM_IOCTL; i++) { if (cmd32 == atm_ioctl_map[i].cmd32) { cmd = atm_ioctl_map[i].cmd; break; } } if (i == NR_ATM_IOCTL) return -EINVAL; switch (cmd) { case ATM_GETNAMES: return do_atm_iobuf(fd, cmd, arg); case ATM_GETLINKRATE: case ATM_GETTYPE: case ATM_GETESI: case ATM_GETADDR: case ATM_RSTADDR: case ATM_ADDADDR: case ATM_DELADDR: case ATM_GETCIRANGE: case ATM_SETCIRANGE: case ATM_SETESI: case ATM_SETESIF: case ATM_GETSTAT: case ATM_GETSTATZ: case ATM_GETLOOP: case ATM_SETLOOP: case ATM_QUERYLOOP: return do_atmif_sioc(fd, cmd, arg); } return -EINVAL; } static __attribute_used__ int ret_einval(unsigned int fd, unsigned int cmd, unsigned long arg) { return -EINVAL; } #ifdef CONFIG_BLOCK static int broken_blkgetsize(unsigned int fd, unsigned int cmd, unsigned long arg) { /* The mkswap binary hard codes it to Intel value :-((( */ return w_long(fd, BLKGETSIZE, arg); } struct blkpg_ioctl_arg32 { compat_int_t op; compat_int_t flags; compat_int_t datalen; compat_caddr_t data; }; static int blkpg_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { struct blkpg_ioctl_arg32 __user *ua32 = compat_ptr(arg); struct blkpg_ioctl_arg __user *a = compat_alloc_user_space(sizeof(*a)); compat_caddr_t udata; compat_int_t n; int err; err = get_user(n, &ua32->op); err |= put_user(n, &a->op); err |= get_user(n, &ua32->flags); err |= put_user(n, &a->flags); err |= get_user(n, &ua32->datalen); err |= put_user(n, &a->datalen); err |= get_user(udata, &ua32->data); err |= put_user(compat_ptr(udata), &a->data); if (err) return err; return sys_ioctl(fd, cmd, (unsigned long)a); } #endif static int ioc_settimeout(unsigned int fd, unsigned int cmd, unsigned long arg) { return rw_long(fd, AUTOFS_IOC_SETTIMEOUT, arg); } #ifdef CONFIG_BLOCK /* Fix sizeof(sizeof()) breakage */ #define BLKBSZGET_32 _IOR(0x12,112,int) #define BLKBSZSET_32 _IOW(0x12,113,int) #define BLKGETSIZE64_32 _IOR(0x12,114,int) static int do_blkbszget(unsigned int fd, unsigned int cmd, unsigned long arg) { return sys_ioctl(fd, BLKBSZGET, (unsigned long)compat_ptr(arg)); } static int do_blkbszset(unsigned int fd, unsigned int cmd, unsigned long arg) { return sys_ioctl(fd, BLKBSZSET, (unsigned long)compat_ptr(arg)); } static int do_blkgetsize64(unsigned int fd, unsigned int cmd, unsigned long arg) { return sys_ioctl(fd, BLKGETSIZE64, (unsigned long)compat_ptr(arg)); } #endif /* Bluetooth ioctls */ #define HCIUARTSETPROTO _IOW('U', 200, int) #define HCIUARTGETPROTO _IOR('U', 201, int) #define BNEPCONNADD _IOW('B', 200, int) #define BNEPCONNDEL _IOW('B', 201, int) #define BNEPGETCONNLIST _IOR('B', 210, int) #define BNEPGETCONNINFO _IOR('B', 211, int) #define CMTPCONNADD _IOW('C', 200, int) #define CMTPCONNDEL _IOW('C', 201, int) #define CMTPGETCONNLIST _IOR('C', 210, int) #define CMTPGETCONNINFO _IOR('C', 211, int) #define HIDPCONNADD _IOW('H', 200, int) #define HIDPCONNDEL _IOW('H', 201, int) #define HIDPGETCONNLIST _IOR('H', 210, int) #define HIDPGETCONNINFO _IOR('H', 211, int) #ifdef CONFIG_BLOCK struct floppy_struct32 { compat_uint_t size; compat_uint_t sect; compat_uint_t head; compat_uint_t track; compat_uint_t stretch; unsigned char gap; unsigned char rate; unsigned char spec1; unsigned char fmt_gap; const compat_caddr_t name; }; struct floppy_drive_params32 { char cmos; compat_ulong_t max_dtr; compat_ulong_t hlt; compat_ulong_t hut; compat_ulong_t srt; compat_ulong_t spinup; compat_ulong_t spindown; unsigned char spindown_offset; unsigned char select_delay; unsigned char rps; unsigned char tracks; compat_ulong_t timeout; unsigned char interleave_sect; struct floppy_max_errors max_errors; char flags; char read_track; short autodetect[8]; compat_int_t checkfreq; compat_int_t native_format; }; struct floppy_drive_struct32 { signed char flags; compat_ulong_t spinup_date; compat_ulong_t select_date; compat_ulong_t first_read_date; short probed_format; short track; short maxblock; short maxtrack; compat_int_t generation; compat_int_t keep_data; compat_int_t fd_ref; compat_int_t fd_device; compat_int_t last_checked; compat_caddr_t dmabuf; compat_int_t bufblocks; }; struct floppy_fdc_state32 { compat_int_t spec1; compat_int_t spec2; compat_int_t dtr; unsigned char version; unsigned char dor; compat_ulong_t address; unsigned int rawcmd:2; unsigned int reset:1; unsigned int need_configure:1; unsigned int perp_mode:2; unsigned int has_fifo:1; unsigned int driver_version; unsigned char track[4]; }; struct floppy_write_errors32 { unsigned int write_errors; compat_ulong_t first_error_sector; compat_int_t first_error_generation; compat_ulong_t last_error_sector; compat_int_t last_error_generation; compat_uint_t badness; }; #define FDSETPRM32 _IOW(2, 0x42, struct floppy_struct32) #define FDDEFPRM32 _IOW(2, 0x43, struct floppy_struct32) #define FDGETPRM32 _IOR(2, 0x04, struct floppy_struct32) #define FDSETDRVPRM32 _IOW(2, 0x90, struct floppy_drive_params32) #define FDGETDRVPRM32 _IOR(2, 0x11, struct floppy_drive_params32) #define FDGETDRVSTAT32 _IOR(2, 0x12, struct floppy_drive_struct32) #define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct floppy_drive_struct32) #define FDGETFDCSTAT32 _IOR(2, 0x15, struct floppy_fdc_state32) #define FDWERRORGET32 _IOR(2, 0x17, struct floppy_write_errors32) static struct { unsigned int cmd32; unsigned int cmd; } fd_ioctl_trans_table[] = { { FDSETPRM32, FDSETPRM }, { FDDEFPRM32, FDDEFPRM }, { FDGETPRM32, FDGETPRM }, { FDSETDRVPRM32, FDSETDRVPRM }, { FDGETDRVPRM32, FDGETDRVPRM }, { FDGETDRVSTAT32, FDGETDRVSTAT }, { FDPOLLDRVSTAT32, FDPOLLDRVSTAT }, { FDGETFDCSTAT32, FDGETFDCSTAT }, { FDWERRORGET32, FDWERRORGET } }; #define NR_FD_IOCTL_TRANS ARRAY_SIZE(fd_ioctl_trans_table) static int fd_ioctl_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs = get_fs(); void *karg = NULL; unsigned int kcmd = 0; int i, err; for (i = 0; i < NR_FD_IOCTL_TRANS; i++) if (cmd == fd_ioctl_trans_table[i].cmd32) { kcmd = fd_ioctl_trans_table[i].cmd; break; } if (!kcmd) return -EINVAL; switch (cmd) { case FDSETPRM32: case FDDEFPRM32: case FDGETPRM32: { compat_uptr_t name; struct floppy_struct32 __user *uf; struct floppy_struct *f; uf = compat_ptr(arg); f = karg = kmalloc(sizeof(struct floppy_struct), GFP_KERNEL); if (!karg) return -ENOMEM; if (cmd == FDGETPRM32) break; err = __get_user(f->size, &uf->size); err |= __get_user(f->sect, &uf->sect); err |= __get_user(f->head, &uf->head); err |= __get_user(f->track, &uf->track); err |= __get_user(f->stretch, &uf->stretch); err |= __get_user(f->gap, &uf->gap); err |= __get_user(f->rate, &uf->rate); err |= __get_user(f->spec1, &uf->spec1); err |= __get_user(f->fmt_gap, &uf->fmt_gap); err |= __get_user(name, &uf->name); f->name = compat_ptr(name); if (err) { err = -EFAULT; goto out; } break; } case FDSETDRVPRM32: case FDGETDRVPRM32: { struct floppy_drive_params32 __user *uf; struct floppy_drive_params *f; uf = compat_ptr(arg); f = karg = kmalloc(sizeof(struct floppy_drive_params), GFP_KERNEL); if (!karg) return -ENOMEM; if (cmd == FDGETDRVPRM32) break; err = __get_user(f->cmos, &uf->cmos); err |= __get_user(f->max_dtr, &uf->max_dtr); err |= __get_user(f->hlt, &uf->hlt); err |= __get_user(f->hut, &uf->hut); err |= __get_user(f->srt, &uf->srt); err |= __get_user(f->spinup, &uf->spinup); err |= __get_user(f->spindown, &uf->spindown); err |= __get_user(f->spindown_offset, &uf->spindown_offset); err |= __get_user(f->select_delay, &uf->select_delay); err |= __get_user(f->rps, &uf->rps); err |= __get_user(f->tracks, &uf->tracks); err |= __get_user(f->timeout, &uf->timeout); err |= __get_user(f->interleave_sect, &uf->interleave_sect); err |= __copy_from_user(&f->max_errors, &uf->max_errors, sizeof(f->max_errors)); err |= __get_user(f->flags, &uf->flags); err |= __get_user(f->read_track, &uf->read_track); err |= __copy_from_user(f->autodetect, uf->autodetect, sizeof(f->autodetect)); err |= __get_user(f->checkfreq, &uf->checkfreq); err |= __get_user(f->native_format, &uf->native_format); if (err) { err = -EFAULT; goto out; } break; } case FDGETDRVSTAT32: case FDPOLLDRVSTAT32: karg = kmalloc(sizeof(struct floppy_drive_struct), GFP_KERNEL); if (!karg) return -ENOMEM; break; case FDGETFDCSTAT32: karg = kmalloc(sizeof(struct floppy_fdc_state), GFP_KERNEL); if (!karg) return -ENOMEM; break; case FDWERRORGET32: karg = kmalloc(sizeof(struct floppy_write_errors), GFP_KERNEL); if (!karg) return -ENOMEM; break; default: return -EINVAL; } set_fs (KERNEL_DS); err = sys_ioctl (fd, kcmd, (unsigned long)karg); set_fs (old_fs); if (err) goto out; switch (cmd) { case FDGETPRM32: { struct floppy_struct *f = karg; struct floppy_struct32 __user *uf = compat_ptr(arg); err = __put_user(f->size, &uf->size); err |= __put_user(f->sect, &uf->sect); err |= __put_user(f->head, &uf->head); err |= __put_user(f->track, &uf->track); err |= __put_user(f->stretch, &uf->stretch); err |= __put_user(f->gap, &uf->gap); err |= __put_user(f->rate, &uf->rate); err |= __put_user(f->spec1, &uf->spec1); err |= __put_user(f->fmt_gap, &uf->fmt_gap); err |= __put_user((u64)f->name, (compat_caddr_t __user *)&uf->name); break; } case FDGETDRVPRM32: { struct floppy_drive_params32 __user *uf; struct floppy_drive_params *f = karg; uf = compat_ptr(arg); err = __put_user(f->cmos, &uf->cmos); err |= __put_user(f->max_dtr, &uf->max_dtr); err |= __put_user(f->hlt, &uf->hlt); err |= __put_user(f->hut, &uf->hut); err |= __put_user(f->srt, &uf->srt); err |= __put_user(f->spinup, &uf->spinup); err |= __put_user(f->spindown, &uf->spindown); err |= __put_user(f->spindown_offset, &uf->spindown_offset); err |= __put_user(f->select_delay, &uf->select_delay); err |= __put_user(f->rps, &uf->rps); err |= __put_user(f->tracks, &uf->tracks); err |= __put_user(f->timeout, &uf->timeout); err |= __put_user(f->interleave_sect, &uf->interleave_sect); err |= __copy_to_user(&uf->max_errors, &f->max_errors, sizeof(f->max_errors)); err |= __put_user(f->flags, &uf->flags); err |= __put_user(f->read_track, &uf->read_track); err |= __copy_to_user(uf->autodetect, f->autodetect, sizeof(f->autodetect)); err |= __put_user(f->checkfreq, &uf->checkfreq); err |= __put_user(f->native_format, &uf->native_format); break; } case FDGETDRVSTAT32: case FDPOLLDRVSTAT32: { struct floppy_drive_struct32 __user *uf; struct floppy_drive_struct *f = karg; uf = compat_ptr(arg); err = __put_user(f->flags, &uf->flags); err |= __put_user(f->spinup_date, &uf->spinup_date); err |= __put_user(f->select_date, &uf->select_date); err |= __put_user(f->first_read_date, &uf->first_read_date); err |= __put_user(f->probed_format, &uf->probed_format); err |= __put_user(f->track, &uf->track); err |= __put_user(f->maxblock, &uf->maxblock); err |= __put_user(f->maxtrack, &uf->maxtrack); err |= __put_user(f->generation, &uf->generation); err |= __put_user(f->keep_data, &uf->keep_data); err |= __put_user(f->fd_ref, &uf->fd_ref); err |= __put_user(f->fd_device, &uf->fd_device); err |= __put_user(f->last_checked, &uf->last_checked); err |= __put_user((u64)f->dmabuf, &uf->dmabuf); err |= __put_user((u64)f->bufblocks, &uf->bufblocks); break; } case FDGETFDCSTAT32: { struct floppy_fdc_state32 __user *uf; struct floppy_fdc_state *f = karg; uf = compat_ptr(arg); err = __put_user(f->spec1, &uf->spec1); err |= __put_user(f->spec2, &uf->spec2); err |= __put_user(f->dtr, &uf->dtr); err |= __put_user(f->version, &uf->version); err |= __put_user(f->dor, &uf->dor); err |= __put_user(f->address, &uf->address); err |= __copy_to_user((char __user *)&uf->address + sizeof(uf->address), (char *)&f->address + sizeof(f->address), sizeof(int)); err |= __put_user(f->driver_version, &uf->driver_version); err |= __copy_to_user(uf->track, f->track, sizeof(f->track)); break; } case FDWERRORGET32: { struct floppy_write_errors32 __user *uf; struct floppy_write_errors *f = karg; uf = compat_ptr(arg); err = __put_user(f->write_errors, &uf->write_errors); err |= __put_user(f->first_error_sector, &uf->first_error_sector); err |= __put_user(f->first_error_generation, &uf->first_error_generation); err |= __put_user(f->last_error_sector, &uf->last_error_sector); err |= __put_user(f->last_error_generation, &uf->last_error_generation); err |= __put_user(f->badness, &uf->badness); break; } default: break; } if (err) err = -EFAULT; out: kfree(karg); return err; } #endif struct mtd_oob_buf32 { u_int32_t start; u_int32_t length; compat_caddr_t ptr; /* unsigned char* */ }; #define MEMWRITEOOB32 _IOWR('M',3,struct mtd_oob_buf32) #define MEMREADOOB32 _IOWR('M',4,struct mtd_oob_buf32) static int mtd_rw_oob(unsigned int fd, unsigned int cmd, unsigned long arg) { struct mtd_oob_buf __user *buf = compat_alloc_user_space(sizeof(*buf)); struct mtd_oob_buf32 __user *buf32 = compat_ptr(arg); u32 data; char __user *datap; unsigned int real_cmd; int err; real_cmd = (cmd == MEMREADOOB32) ? MEMREADOOB : MEMWRITEOOB; if (copy_in_user(&buf->start, &buf32->start, 2 * sizeof(u32)) || get_user(data, &buf32->ptr)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &buf->ptr)) return -EFAULT; err = sys_ioctl(fd, real_cmd, (unsigned long) buf); if (!err) { if (copy_in_user(&buf32->start, &buf->start, 2 * sizeof(u32))) err = -EFAULT; } return err; } #ifdef CONFIG_BLOCK struct raw32_config_request { compat_int_t raw_minor; __u64 block_major; __u64 block_minor; } __attribute__((packed)); static int get_raw32_request(struct raw_config_request *req, struct raw32_config_request __user *user_req) { int ret; if (!access_ok(VERIFY_READ, user_req, sizeof(struct raw32_config_request))) return -EFAULT; ret = __get_user(req->raw_minor, &user_req->raw_minor); ret |= __get_user(req->block_major, &user_req->block_major); ret |= __get_user(req->block_minor, &user_req->block_minor); return ret ? -EFAULT : 0; } static int set_raw32_request(struct raw_config_request *req, struct raw32_config_request __user *user_req) { int ret; if (!access_ok(VERIFY_WRITE, user_req, sizeof(struct raw32_config_request))) return -EFAULT; ret = __put_user(req->raw_minor, &user_req->raw_minor); ret |= __put_user(req->block_major, &user_req->block_major); ret |= __put_user(req->block_minor, &user_req->block_minor); return ret ? -EFAULT : 0; } static int raw_ioctl(unsigned fd, unsigned cmd, unsigned long arg) { int ret; switch (cmd) { case RAW_SETBIND: case RAW_GETBIND: { struct raw_config_request req; struct raw32_config_request __user *user_req = compat_ptr(arg); mm_segment_t oldfs = get_fs(); if ((ret = get_raw32_request(&req, user_req))) return ret; set_fs(KERNEL_DS); ret = sys_ioctl(fd,cmd,(unsigned long)&req); set_fs(oldfs); if ((!ret) && (cmd == RAW_GETBIND)) { ret = set_raw32_request(&req, user_req); } break; } default: ret = sys_ioctl(fd, cmd, arg); break; } return ret; } #endif /* CONFIG_BLOCK */ struct serial_struct32 { compat_int_t type; compat_int_t line; compat_uint_t port; compat_int_t irq; compat_int_t flags; compat_int_t xmit_fifo_size; compat_int_t custom_divisor; compat_int_t baud_base; unsigned short close_delay; char io_type; char reserved_char[1]; compat_int_t hub6; unsigned short closing_wait; /* time to wait before closing */ unsigned short closing_wait2; /* no longer used... */ compat_uint_t iomem_base; unsigned short iomem_reg_shift; unsigned int port_high; /* compat_ulong_t iomap_base FIXME */ compat_int_t reserved[1]; }; static int serial_struct_ioctl(unsigned fd, unsigned cmd, unsigned long arg) { typedef struct serial_struct SS; typedef struct serial_struct32 SS32; struct serial_struct32 __user *ss32 = compat_ptr(arg); int err; struct serial_struct ss; mm_segment_t oldseg = get_fs(); __u32 udata; unsigned int base; if (cmd == TIOCSSERIAL) { if (!access_ok(VERIFY_READ, ss32, sizeof(SS32))) return -EFAULT; if (__copy_from_user(&ss, ss32, offsetof(SS32, iomem_base))) return -EFAULT; if (__get_user(udata, &ss32->iomem_base)) return -EFAULT; ss.iomem_base = compat_ptr(udata); if (__get_user(ss.iomem_reg_shift, &ss32->iomem_reg_shift) || __get_user(ss.port_high, &ss32->port_high)) return -EFAULT; ss.iomap_base = 0UL; } set_fs(KERNEL_DS); err = sys_ioctl(fd,cmd,(unsigned long)(&ss)); set_fs(oldseg); if (cmd == TIOCGSERIAL && err >= 0) { if (!access_ok(VERIFY_WRITE, ss32, sizeof(SS32))) return -EFAULT; if (__copy_to_user(ss32,&ss,offsetof(SS32,iomem_base))) return -EFAULT; base = (unsigned long)ss.iomem_base >> 32 ? 0xffffffff : (unsigned)(unsigned long)ss.iomem_base; if (__put_user(base, &ss32->iomem_base) || __put_user(ss.iomem_reg_shift, &ss32->iomem_reg_shift) || __put_user(ss.port_high, &ss32->port_high)) return -EFAULT; } return err; } struct usbdevfs_ctrltransfer32 { u8 bRequestType; u8 bRequest; u16 wValue; u16 wIndex; u16 wLength; u32 timeout; /* in milliseconds */ compat_caddr_t data; }; #define USBDEVFS_CONTROL32 _IOWR('U', 0, struct usbdevfs_ctrltransfer32) static int do_usbdevfs_control(unsigned int fd, unsigned int cmd, unsigned long arg) { struct usbdevfs_ctrltransfer32 __user *p32 = compat_ptr(arg); struct usbdevfs_ctrltransfer __user *p; __u32 udata; p = compat_alloc_user_space(sizeof(*p)); if (copy_in_user(p, p32, (sizeof(*p32) - sizeof(compat_caddr_t))) || get_user(udata, &p32->data) || put_user(compat_ptr(udata), &p->data)) return -EFAULT; return sys_ioctl(fd, USBDEVFS_CONTROL, (unsigned long)p); } struct usbdevfs_bulktransfer32 { compat_uint_t ep; compat_uint_t len; compat_uint_t timeout; /* in milliseconds */ compat_caddr_t data; }; #define USBDEVFS_BULK32 _IOWR('U', 2, struct usbdevfs_bulktransfer32) static int do_usbdevfs_bulk(unsigned int fd, unsigned int cmd, unsigned long arg) { struct usbdevfs_bulktransfer32 __user *p32 = compat_ptr(arg); struct usbdevfs_bulktransfer __user *p; compat_uint_t n; compat_caddr_t addr; p = compat_alloc_user_space(sizeof(*p)); if (get_user(n, &p32->ep) || put_user(n, &p->ep) || get_user(n, &p32->len) || put_user(n, &p->len) || get_user(n, &p32->timeout) || put_user(n, &p->timeout) || get_user(addr, &p32->data) || put_user(compat_ptr(addr), &p->data)) return -EFAULT; return sys_ioctl(fd, USBDEVFS_BULK, (unsigned long)p); } /* * USBDEVFS_SUBMITURB, USBDEVFS_REAPURB and USBDEVFS_REAPURBNDELAY * are handled in usbdevfs core. -Christopher Li */ struct usbdevfs_disconnectsignal32 { compat_int_t signr; compat_caddr_t context; }; #define USBDEVFS_DISCSIGNAL32 _IOR('U', 14, struct usbdevfs_disconnectsignal32) static int do_usbdevfs_discsignal(unsigned int fd, unsigned int cmd, unsigned long arg) { struct usbdevfs_disconnectsignal kdis; struct usbdevfs_disconnectsignal32 __user *udis; mm_segment_t old_fs; u32 uctx; int err; udis = compat_ptr(arg); if (get_user(kdis.signr, &udis->signr) || __get_user(uctx, &udis->context)) return -EFAULT; kdis.context = compat_ptr(uctx); old_fs = get_fs(); set_fs(KERNEL_DS); err = sys_ioctl(fd, USBDEVFS_DISCSIGNAL, (unsigned long) &kdis); set_fs(old_fs); return err; } /* * I2C layer ioctls */ struct i2c_msg32 { u16 addr; u16 flags; u16 len; compat_caddr_t buf; }; struct i2c_rdwr_ioctl_data32 { compat_caddr_t msgs; /* struct i2c_msg __user *msgs */ u32 nmsgs; }; struct i2c_smbus_ioctl_data32 { u8 read_write; u8 command; u32 size; compat_caddr_t data; /* union i2c_smbus_data *data */ }; struct i2c_rdwr_aligned { struct i2c_rdwr_ioctl_data cmd; struct i2c_msg msgs[0]; }; static int do_i2c_rdwr_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct i2c_rdwr_ioctl_data32 __user *udata = compat_ptr(arg); struct i2c_rdwr_aligned __user *tdata; struct i2c_msg __user *tmsgs; struct i2c_msg32 __user *umsgs; compat_caddr_t datap; int nmsgs, i; if (get_user(nmsgs, &udata->nmsgs)) return -EFAULT; if (nmsgs > I2C_RDRW_IOCTL_MAX_MSGS) return -EINVAL; if (get_user(datap, &udata->msgs)) return -EFAULT; umsgs = compat_ptr(datap); tdata = compat_alloc_user_space(sizeof(*tdata) + nmsgs * sizeof(struct i2c_msg)); tmsgs = &tdata->msgs[0]; if (put_user(nmsgs, &tdata->cmd.nmsgs) || put_user(tmsgs, &tdata->cmd.msgs)) return -EFAULT; for (i = 0; i < nmsgs; i++) { if (copy_in_user(&tmsgs[i].addr, &umsgs[i].addr, 3*sizeof(u16))) return -EFAULT; if (get_user(datap, &umsgs[i].buf) || put_user(compat_ptr(datap), &tmsgs[i].buf)) return -EFAULT; } return sys_ioctl(fd, cmd, (unsigned long)tdata); } static int do_i2c_smbus_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct i2c_smbus_ioctl_data __user *tdata; struct i2c_smbus_ioctl_data32 __user *udata; compat_caddr_t datap; tdata = compat_alloc_user_space(sizeof(*tdata)); if (tdata == NULL) return -ENOMEM; if (!access_ok(VERIFY_WRITE, tdata, sizeof(*tdata))) return -EFAULT; udata = compat_ptr(arg); if (!access_ok(VERIFY_READ, udata, sizeof(*udata))) return -EFAULT; if (__copy_in_user(&tdata->read_write, &udata->read_write, 2 * sizeof(u8))) return -EFAULT; if (__copy_in_user(&tdata->size, &udata->size, 2 * sizeof(u32))) return -EFAULT; if (__get_user(datap, &udata->data) || __put_user(compat_ptr(datap), &tdata->data)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long)tdata); } struct compat_iw_point { compat_caddr_t pointer; __u16 length; __u16 flags; }; static int do_wireless_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct iwreq __user *iwr; struct iwreq __user *iwr_u; struct iw_point __user *iwp; struct compat_iw_point __user *iwp_u; compat_caddr_t pointer; __u16 length, flags; iwr_u = compat_ptr(arg); iwp_u = (struct compat_iw_point __user *) &iwr_u->u.data; iwr = compat_alloc_user_space(sizeof(*iwr)); if (iwr == NULL) return -ENOMEM; iwp = &iwr->u.data; if (!access_ok(VERIFY_WRITE, iwr, sizeof(*iwr))) return -EFAULT; if (__copy_in_user(&iwr->ifr_ifrn.ifrn_name[0], &iwr_u->ifr_ifrn.ifrn_name[0], sizeof(iwr->ifr_ifrn.ifrn_name))) return -EFAULT; if (__get_user(pointer, &iwp_u->pointer) || __get_user(length, &iwp_u->length) || __get_user(flags, &iwp_u->flags)) return -EFAULT; if (__put_user(compat_ptr(pointer), &iwp->pointer) || __put_user(length, &iwp->length) || __put_user(flags, &iwp->flags)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long) iwr); } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatiable ioctls */ static int old_bridge_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { u32 tmp; if (get_user(tmp, (u32 __user *) arg)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } #define RTC_IRQP_READ32 _IOR('p', 0x0b, compat_ulong_t) #define RTC_IRQP_SET32 _IOW('p', 0x0c, compat_ulong_t) #define RTC_EPOCH_READ32 _IOR('p', 0x0d, compat_ulong_t) #define RTC_EPOCH_SET32 _IOW('p', 0x0e, compat_ulong_t) static int rtc_ioctl(unsigned fd, unsigned cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); compat_ulong_t val32; unsigned long kval; int ret; switch (cmd) { case RTC_IRQP_READ32: case RTC_EPOCH_READ32: set_fs(KERNEL_DS); ret = sys_ioctl(fd, (cmd == RTC_IRQP_READ32) ? RTC_IRQP_READ : RTC_EPOCH_READ, (unsigned long)&kval); set_fs(oldfs); if (ret) return ret; val32 = kval; return put_user(val32, (unsigned int __user *)arg); case RTC_IRQP_SET32: return sys_ioctl(fd, RTC_IRQP_SET, arg); case RTC_EPOCH_SET32: return sys_ioctl(fd, RTC_EPOCH_SET, arg); default: /* unreached */ return -ENOIOCTLCMD; } } static int lp_timeout_trans(unsigned int fd, unsigned int cmd, unsigned long arg) { struct compat_timeval __user *tc = (struct compat_timeval __user *)arg; struct timeval __user *tn = compat_alloc_user_space(sizeof(struct timeval)); struct timeval ts; if (get_user(ts.tv_sec, &tc->tv_sec) || get_user(ts.tv_usec, &tc->tv_usec) || put_user(ts.tv_sec, &tn->tv_sec) || put_user(ts.tv_usec, &tn->tv_usec)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long)tn); } #define HANDLE_IOCTL(cmd,handler) \ { (cmd), (ioctl_trans_handler_t)(handler) }, /* pointer to compatible structure or no argument */ #define COMPATIBLE_IOCTL(cmd) \ { (cmd), do_ioctl32_pointer }, /* argument is an unsigned long integer, not a pointer */ #define ULONG_IOCTL(cmd) \ { (cmd), (ioctl_trans_handler_t)sys_ioctl }, struct ioctl_trans ioctl_start[] = { #include <linux/compat_ioctl.h> HANDLE_IOCTL(MEMREADOOB32, mtd_rw_oob) HANDLE_IOCTL(MEMWRITEOOB32, mtd_rw_oob) #ifdef CONFIG_NET HANDLE_IOCTL(SIOCGIFNAME, dev_ifname32) HANDLE_IOCTL(SIOCGIFCONF, dev_ifconf) HANDLE_IOCTL(SIOCGIFFLAGS, dev_ifsioc) HANDLE_IOCTL(SIOCSIFFLAGS, dev_ifsioc) HANDLE_IOCTL(SIOCGIFMETRIC, dev_ifsioc) HANDLE_IOCTL(SIOCSIFMETRIC, dev_ifsioc) HANDLE_IOCTL(SIOCGIFMTU, dev_ifsioc) HANDLE_IOCTL(SIOCSIFMTU, dev_ifsioc) HANDLE_IOCTL(SIOCGIFMEM, dev_ifsioc) HANDLE_IOCTL(SIOCSIFMEM, dev_ifsioc) HANDLE_IOCTL(SIOCGIFHWADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSIFHWADDR, dev_ifsioc) HANDLE_IOCTL(SIOCADDMULTI, dev_ifsioc) HANDLE_IOCTL(SIOCDELMULTI, dev_ifsioc) HANDLE_IOCTL(SIOCGIFINDEX, dev_ifsioc) HANDLE_IOCTL(SIOCGIFMAP, dev_ifsioc) HANDLE_IOCTL(SIOCSIFMAP, dev_ifsioc) HANDLE_IOCTL(SIOCGIFADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSIFADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSIFHWBROADCAST, dev_ifsioc) /* ioctls used by appletalk ddp.c */ HANDLE_IOCTL(SIOCATALKDIFADDR, dev_ifsioc) HANDLE_IOCTL(SIOCDIFADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSARP, dev_ifsioc) HANDLE_IOCTL(SIOCDARP, dev_ifsioc) HANDLE_IOCTL(SIOCGIFBRDADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSIFBRDADDR, dev_ifsioc) HANDLE_IOCTL(SIOCGIFDSTADDR, dev_ifsioc) HANDLE_IOCTL(SIOCSIFDSTADDR, dev_ifsioc) HANDLE_IOCTL(SIOCGIFNETMASK, dev_ifsioc) HANDLE_IOCTL(SIOCSIFNETMASK, dev_ifsioc) HANDLE_IOCTL(SIOCSIFPFLAGS, dev_ifsioc) HANDLE_IOCTL(SIOCGIFPFLAGS, dev_ifsioc) HANDLE_IOCTL(SIOCGIFTXQLEN, dev_ifsioc) HANDLE_IOCTL(SIOCSIFTXQLEN, dev_ifsioc) HANDLE_IOCTL(TUNSETIFF, dev_ifsioc) HANDLE_IOCTL(SIOCETHTOOL, ethtool_ioctl) HANDLE_IOCTL(SIOCBONDENSLAVE, bond_ioctl) HANDLE_IOCTL(SIOCBONDRELEASE, bond_ioctl) HANDLE_IOCTL(SIOCBONDSETHWADDR, bond_ioctl) HANDLE_IOCTL(SIOCBONDSLAVEINFOQUERY, bond_ioctl) HANDLE_IOCTL(SIOCBONDINFOQUERY, bond_ioctl) HANDLE_IOCTL(SIOCBONDCHANGEACTIVE, bond_ioctl) HANDLE_IOCTL(SIOCADDRT, routing_ioctl) HANDLE_IOCTL(SIOCDELRT, routing_ioctl) HANDLE_IOCTL(SIOCBRADDIF, dev_ifsioc) HANDLE_IOCTL(SIOCBRDELIF, dev_ifsioc) /* Note SIOCRTMSG is no longer, so this is safe and * the user would have seen just an -EINVAL anyways. */ HANDLE_IOCTL(SIOCRTMSG, ret_einval) HANDLE_IOCTL(SIOCGSTAMP, do_siocgstamp) #endif #ifdef CONFIG_BLOCK HANDLE_IOCTL(HDIO_GETGEO, hdio_getgeo) HANDLE_IOCTL(BLKRAGET, w_long) HANDLE_IOCTL(BLKGETSIZE, w_long) HANDLE_IOCTL(0x1260, broken_blkgetsize) HANDLE_IOCTL(BLKFRAGET, w_long) HANDLE_IOCTL(BLKSECTGET, w_long) HANDLE_IOCTL(BLKPG, blkpg_ioctl_trans) HANDLE_IOCTL(HDIO_GET_UNMASKINTR, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_MULTCOUNT, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_KEEPSETTINGS, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_32BIT, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_NOWERR, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_DMA, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_NICE, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_WCACHE, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_ACOUSTIC, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_ADDRESS, hdio_ioctl_trans) HANDLE_IOCTL(HDIO_GET_BUSSTATE, hdio_ioctl_trans) HANDLE_IOCTL(FDSETPRM32, fd_ioctl_trans) HANDLE_IOCTL(FDDEFPRM32, fd_ioctl_trans) HANDLE_IOCTL(FDGETPRM32, fd_ioctl_trans) HANDLE_IOCTL(FDSETDRVPRM32, fd_ioctl_trans) HANDLE_IOCTL(FDGETDRVPRM32, fd_ioctl_trans) HANDLE_IOCTL(FDGETDRVSTAT32, fd_ioctl_trans) HANDLE_IOCTL(FDPOLLDRVSTAT32, fd_ioctl_trans) HANDLE_IOCTL(FDGETFDCSTAT32, fd_ioctl_trans) HANDLE_IOCTL(FDWERRORGET32, fd_ioctl_trans) HANDLE_IOCTL(SG_IO,sg_ioctl_trans) HANDLE_IOCTL(SG_GET_REQUEST_TABLE, sg_grt_trans) #endif HANDLE_IOCTL(PPPIOCGIDLE32, ppp_ioctl_trans) HANDLE_IOCTL(PPPIOCSCOMPRESS32, ppp_ioctl_trans) HANDLE_IOCTL(PPPIOCSPASS32, ppp_sock_fprog_ioctl_trans) HANDLE_IOCTL(PPPIOCSACTIVE32, ppp_sock_fprog_ioctl_trans) #ifdef CONFIG_BLOCK HANDLE_IOCTL(MTIOCGET32, mt_ioctl_trans) HANDLE_IOCTL(MTIOCPOS32, mt_ioctl_trans) HANDLE_IOCTL(CDROMREADAUDIO, cdrom_ioctl_trans) HANDLE_IOCTL(CDROM_SEND_PACKET, cdrom_ioctl_trans) #endif #define AUTOFS_IOC_SETTIMEOUT32 _IOWR(0x93,0x64,unsigned int) HANDLE_IOCTL(AUTOFS_IOC_SETTIMEOUT32, ioc_settimeout) #ifdef CONFIG_VT HANDLE_IOCTL(PIO_FONTX, do_fontx_ioctl) HANDLE_IOCTL(GIO_FONTX, do_fontx_ioctl) HANDLE_IOCTL(PIO_UNIMAP, do_unimap_ioctl) HANDLE_IOCTL(GIO_UNIMAP, do_unimap_ioctl) HANDLE_IOCTL(KDFONTOP, do_kdfontop_ioctl) #endif /* One SMB ioctl needs translations. */ #define SMB_IOC_GETMOUNTUID_32 _IOR('u', 1, compat_uid_t) HANDLE_IOCTL(SMB_IOC_GETMOUNTUID_32, do_smb_getmountuid) HANDLE_IOCTL(ATM_GETLINKRATE32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETNAMES32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETTYPE32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETESI32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETADDR32, do_atm_ioctl) HANDLE_IOCTL(ATM_RSTADDR32, do_atm_ioctl) HANDLE_IOCTL(ATM_ADDADDR32, do_atm_ioctl) HANDLE_IOCTL(ATM_DELADDR32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETCIRANGE32, do_atm_ioctl) HANDLE_IOCTL(ATM_SETCIRANGE32, do_atm_ioctl) HANDLE_IOCTL(ATM_SETESI32, do_atm_ioctl) HANDLE_IOCTL(ATM_SETESIF32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETSTAT32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETSTATZ32, do_atm_ioctl) HANDLE_IOCTL(ATM_GETLOOP32, do_atm_ioctl) HANDLE_IOCTL(ATM_SETLOOP32, do_atm_ioctl) HANDLE_IOCTL(ATM_QUERYLOOP32, do_atm_ioctl) HANDLE_IOCTL(SONET_GETSTAT, do_atm_ioctl) HANDLE_IOCTL(SONET_GETSTATZ, do_atm_ioctl) HANDLE_IOCTL(SONET_GETDIAG, do_atm_ioctl) HANDLE_IOCTL(SONET_SETDIAG, do_atm_ioctl) HANDLE_IOCTL(SONET_CLRDIAG, do_atm_ioctl) HANDLE_IOCTL(SONET_SETFRAMING, do_atm_ioctl) HANDLE_IOCTL(SONET_GETFRAMING, do_atm_ioctl) HANDLE_IOCTL(SONET_GETFRSENSE, do_atm_ioctl) /* block stuff */ #ifdef CONFIG_BLOCK HANDLE_IOCTL(BLKBSZGET_32, do_blkbszget) HANDLE_IOCTL(BLKBSZSET_32, do_blkbszset) HANDLE_IOCTL(BLKGETSIZE64_32, do_blkgetsize64) /* Raw devices */ HANDLE_IOCTL(RAW_SETBIND, raw_ioctl) HANDLE_IOCTL(RAW_GETBIND, raw_ioctl) #endif /* Serial */ HANDLE_IOCTL(TIOCGSERIAL, serial_struct_ioctl) HANDLE_IOCTL(TIOCSSERIAL, serial_struct_ioctl) #ifdef TIOCGLTC COMPATIBLE_IOCTL(TIOCGLTC) COMPATIBLE_IOCTL(TIOCSLTC) #endif #ifdef TIOCSTART /* * For these two we have defintions in ioctls.h and/or termios.h on * some architectures but no actual implemention. Some applications * like bash call them if they are defined in the headers, so we provide * entries here to avoid syslog message spew. */ COMPATIBLE_IOCTL(TIOCSTART) COMPATIBLE_IOCTL(TIOCSTOP) #endif /* Usbdevfs */ HANDLE_IOCTL(USBDEVFS_CONTROL32, do_usbdevfs_control) HANDLE_IOCTL(USBDEVFS_BULK32, do_usbdevfs_bulk) HANDLE_IOCTL(USBDEVFS_DISCSIGNAL32, do_usbdevfs_discsignal) COMPATIBLE_IOCTL(USBDEVFS_IOCTL32) /* i2c */ HANDLE_IOCTL(I2C_FUNCS, w_long) HANDLE_IOCTL(I2C_RDWR, do_i2c_rdwr_ioctl) HANDLE_IOCTL(I2C_SMBUS, do_i2c_smbus_ioctl) /* wireless */ HANDLE_IOCTL(SIOCGIWRANGE, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWPRIV, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWSTATS, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWSPY, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWSPY, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWTHRSPY, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWTHRSPY, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWMLME, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWAPLIST, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWSCAN, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWSCAN, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWESSID, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWESSID, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWNICKN, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWNICKN, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWENCODE, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWENCODE, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWGENIE, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWGENIE, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWENCODEEXT, do_wireless_ioctl) HANDLE_IOCTL(SIOCGIWENCODEEXT, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIWPMKSA, do_wireless_ioctl) HANDLE_IOCTL(SIOCSIFBR, old_bridge_ioctl) HANDLE_IOCTL(SIOCGIFBR, old_bridge_ioctl) HANDLE_IOCTL(RTC_IRQP_READ32, rtc_ioctl) HANDLE_IOCTL(RTC_IRQP_SET32, rtc_ioctl) HANDLE_IOCTL(RTC_EPOCH_READ32, rtc_ioctl) HANDLE_IOCTL(RTC_EPOCH_SET32, rtc_ioctl) /* dvb */ HANDLE_IOCTL(VIDEO_GET_EVENT, do_video_get_event) HANDLE_IOCTL(VIDEO_STILLPICTURE, do_video_stillpicture) HANDLE_IOCTL(VIDEO_SET_SPU_PALETTE, do_video_set_spu_palette) /* parport */ COMPATIBLE_IOCTL(LPTIME) COMPATIBLE_IOCTL(LPCHAR) COMPATIBLE_IOCTL(LPABORTOPEN) COMPATIBLE_IOCTL(LPCAREFUL) COMPATIBLE_IOCTL(LPWAIT) COMPATIBLE_IOCTL(LPSETIRQ) COMPATIBLE_IOCTL(LPGETSTATUS) COMPATIBLE_IOCTL(LPGETSTATUS) COMPATIBLE_IOCTL(LPRESET) /*LPGETSTATS not implemented, but no kernels seem to compile it in anyways*/ COMPATIBLE_IOCTL(LPGETFLAGS) HANDLE_IOCTL(LPSETTIMEOUT, lp_timeout_trans) }; int ioctl_table_size = ARRAY_SIZE(ioctl_start);
mit
StarbuckBG/BTCGPU
src/qt/locale/bitcoin_hi_IN.ts
15201
<TS language="hi_IN" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>पते या लेबल को संपादित करने के लिए राइट-क्लिक करें</translation> </message> <message> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <source>&amp;New</source> <translation>&amp;NEW</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>सूची से वर्तमान में चयनित पता हटाएं</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <source>Bitcoin</source> <translation>बीटकोइन</translation> </message> <message> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Confirmed</source> <translation>पक्का</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>संस्करण</translation> </message> <message> <source>Usage:</source> <translation>खपत :</translation> </message> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>भूल</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>फार्म</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>विकल्प</translation> </message> <message> <source>W&amp;allet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>फार्म</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>N/A</source> <translation>लागू नही </translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <source>&amp;Information</source> <translation>जानकारी</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>राशि :</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>&amp;पता कॉपी करे</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Pay To:</source> <translation>प्राप्तकर्ता:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <source>Specify data directory</source> <translation>डेटा डायरेक्टरी बताएं </translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation> </message> <message> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> </context> </TS>
mit
jennyheath/lions-share
vendor/bundle/ruby/2.1.0/gems/puma-2.12.3/README.md
13538
# Puma: A Ruby Web Server Built For Concurrency [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/puma/puma?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Build Status](https://secure.travis-ci.org/puma/puma.png)](http://travis-ci.org/puma/puma) [![Dependency Status](https://gemnasium.com/puma/puma.png)](https://gemnasium.com/puma/puma) <a href="https://codeclimate.com/github/puma/puma"><img src="https://codeclimate.com/github/puma/puma.png" /></a> ## Description Puma is a simple, fast, threaded, and highly concurrent HTTP 1.1 server for Ruby/Rack applications. Puma is intended for use in both development and production environments. In order to get the best throughput, it is highly recommended that you use a Ruby implementation with real threads like Rubinius or JRuby. ## Built For Speed &amp; Concurrency Puma is a simple, fast, and highly concurrent HTTP 1.1 server for Ruby web applications. It can be used with any application that supports Rack, and is considered the replacement for Webrick and Mongrel. It was designed to be the go-to server for [Rubinius](http://rubini.us), but also works well with JRuby and MRI. Puma is intended for use in both development and production environments. Under the hood, Puma processes requests using a C-optimized Ragel extension (inherited from Mongrel) that provides fast, accurate HTTP 1.1 protocol parsing in a portable way. Puma then serves the request in a thread from an internal thread pool (which you can control). This allows Puma to provide real concurrency for your web application! With Rubinius 2.0, Puma will utilize all cores on your CPU with real threads, meaning you won't have to spawn multiple processes to increase throughput. You can expect to see a similar benefit from JRuby. On MRI, there is a Global Interpreter Lock (GIL) that ensures only one thread can be run at a time. But if you're doing a lot of blocking IO (such as HTTP calls to external APIs like Twitter), Puma still improves MRI's throughput by allowing blocking IO to be run concurrently (EventMachine-based servers such as Thin turn off this ability, requiring you to use special libraries). Your mileage may vary. In order to get the best throughput, it is highly recommended that you use a Ruby implementation with real threads like [Rubinius](http://rubini.us) or [JRuby](http://jruby.org). ## Quick Start The easiest way to get started with Puma is to install it via RubyGems. You can do this easily: $ gem install puma Now you should have the `puma` command available in your PATH, so just do the following in the root folder of your Rack application: $ puma app.ru ## Advanced Setup ### Sinatra You can run your Sinatra application with Puma from the command line like this: $ ruby app.rb -s Puma Or you can configure your application to always use Puma: require 'sinatra' configure { set :server, :puma } If you use Bundler, make sure you add Puma to your Gemfile (see below). ### Rails First, make sure Puma is in your Gemfile: gem 'puma' Then start your server with the `rails` command: $ rails s Puma ### Rackup You can pass it as an option to `rackup`: $ rackup -s Puma Alternatively, you can modify your `config.ru` to choose Puma by default, by adding the following as the first line: #\ -s puma ## Configuration Puma provides numerous options for controlling the operation of the server. Consult `puma -h` (or `puma --help`) for a full list. ### Thread Pool Puma utilizes a dynamic thread pool which you can modify. You can set the minimum and maximum number of threads that are available in the pool with the `-t` (or `--threads`) flag: $ puma -t 8:32 Puma will automatically scale the number of threads based on how much traffic is present. The current default is `0:16`. Feel free to experiment, but be careful not to set the number of maximum threads to a very large number, as you may exhaust resources on the system (or hit resource limits). ### Clustered mode Puma 2 offers clustered mode, allowing you to use forked processes to handle multiple incoming requests concurrently, in addition to threads already provided. You can tune the number of workers with the `-w` (or `--workers`) flag: $ puma -t 8:32 -w 3 On a ruby implementation that offers native threads, you should tune this number to match the number of cores available. Note that threads are still used in clustered mode, and the `-t` thread flag setting is per worker, so `-w 2 -t 16:16` will be 32 threads. If you're running in Clustered Mode you can optionally choose to preload your application before starting up the workers. This is necessary in order to take advantage of the [Copy on Write](http://en.wikipedia.org/wiki/Copy-on-write) feature introduced in [MRI Ruby 2.0](https://blog.heroku.com/archives/2013/3/6/matz_highlights_ruby_2_0_at_waza). To do this simply specify the `--preload` flag in invocation: # CLI invocation $ puma -t 8:32 -w 3 --preload If you're using a configuration file, use the `preload_app!` method, and be sure to specify your config file's location with the `-C` flag: $ puma -C config/puma.rb # config/puma.rb threads 8,32 workers 3 preload_app! Additionally, you can specify a block in your configuration file that will be run on boot of each worker: # config/puma.rb on_worker_boot do # configuration here end This code can be used to setup the process before booting the application, allowing you to do some Puma-specific things that you don't want to embed in your application. For instance, you could fire a log notification that a worker booted or send something to statsd. This can be called multiple times to add hooks. If you're preloading your application and using ActiveRecord, it's recommend you setup your connection pool here: # config/puma.rb on_worker_boot do ActiveSupport.on_load(:active_record) do ActiveRecord::Base.establish_connection end end When you use preload_app, your new code goes all in the master process, and is then copied in the workers (meaning it’s only compatible with cluster mode). General rule is to use preload_app when your workers die often and need fast starts. If you don’t have many workers, you probably should not use preload_app. Note that preload_app can’t be used with phased restart, since phased restart kills and restarts workers one-by-one, and preload_app is all about copying the code of master into the workers. ### Error handler for low-level errors If puma encounters an error outside of the context of your application, it will respond with a 500 and a simple textual error message (see `lowlevel_error` in [this file](https://github.com/puma/puma/blob/master/lib/puma/server.rb)). You can specify custom behavior for this scenario. For example, you can report the error to your third-party error-tracking service (in this example, [rollbar](http://rollbar.com)): ```ruby lowlevel_error_handler do |e| Rollbar.critical(e) [500, {}, ["An error has occurred, and engineers have been informed. Please reload the page. If you continue to have problems, contact [email protected]\n"]] end ``` ### Binding TCP / Sockets In contrast to many other server configs which require multiple flags, Puma simply uses one URI parameter with the `-b` (or `--bind`) flag: $ puma -b tcp://127.0.0.1:9292 Want to use UNIX Sockets instead of TCP (which can provide a 5-10% performance boost)? No problem! $ puma -b unix:///var/run/puma.sock If you need to change the permissions of the UNIX socket, just add a umask parameter: $ puma -b 'unix:///var/run/puma.sock?umask=0111' Need a bit of security? Use SSL sockets! $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert' ### Control/Status Server Puma comes with a builtin status/control app that can be used query and control Puma itself. Here is an example of starting Puma with the control server: $ puma --control tcp://127.0.0.1:9293 --control-token foo This directs Puma to start the control server on localhost port 9293. Additionally, all requests to the control server will need to include `token=foo` as a query parameter. This allows for simple authentication. Check out [status.rb](https://github.com/puma/puma/blob/master/lib/puma/app/status.rb) to see what the app has available. ### Configuration file You can also provide a configuration file which Puma will use with the `-C` (or `--config`) flag: $ puma -C /path/to/config By default, if no configuration file is specifed, Puma will look for a configuration file at config/puma.rb. If an environment is specified, either via the `-e` and `--environment` flags, or through the `RACK_ENV` environment variable, the default file location will be config/puma/environment_name.rb. If you want to prevent Puma from looking for a configuration file in those locations, provide a dash as the argument to the `-C` (or `--config`) flag: $ puma -C "-" Take the following [sample configuration](https://github.com/puma/puma/blob/master/examples/config.rb) as inspiration or check out [configuration.rb](https://github.com/puma/puma/blob/master/lib/puma/configuration.rb) to see all available options. ## Restart Puma includes the ability to restart itself allowing easy upgrades to new versions. When available (MRI, Rubinius, JRuby), Puma performs a "hot restart". This is the same functionality available in *unicorn* and *nginx* which keep the server sockets open between restarts. This makes sure that no pending requests are dropped while the restart is taking place. To perform a restart, there are 2 builtin mechanisms: * Send the `puma` process the `SIGUSR2` signal * Use the status server and issue `/restart` No code is shared between the current and restarted process, so it should be safe to issue a restart any place where you would manually stop Puma and start it again. If the new process is unable to load, it will simply exit. You should therefore run Puma under a supervisor when using it in production. ### Normal vs Hot vs Phased Restart A hot restart means that no requests while deploying your new code will be lost, since the server socket is kept open between restarts. But beware, hot restart does not mean that the incoming requests won’t hang for multiple seconds while your new code has not fully deployed. If you need a zero downtime and zero hanging requests deploy, you must use phased restart. When you run pumactl phased-restart, Puma kills workers one-by-one, meaning that at least another worker is still available to serve requests, which lead in zero hanging request (yay!). But again beware, upgrading an application sometimes involves upgrading the database schema. With phased restart, there may be a moment during the deployment where processes belonging to the previous version and processes belonging to the new version both exist at the same time. Any database schema upgrades you perform must therefore be backwards-compatible with the old application version. if you perform a lot of database migrations, you probably should not use phased restart and use a normal/hot restart instead (pumactl restart). That way, no code is shared while deploying (in that case, preload_app might help for quicker deployment, see below). ### Cleanup Code Puma isn't able to understand all the resources that your app may use, so it provides a hook in the configuration file you pass to `-C` called `on_restart`. The block passed to `on_restart` will be called, unsurprisingly, just before Puma restarts itself. You should place code to close global log files, redis connections, etc in this block so that their file descriptors don't leak into the restarted process. Failure to do so will result in slowly running out of descriptors and eventually obscure crashes as the server is restart many times. ### Platform Constraints Because of various platforms not being implement certain things, the following differences occur when Puma is used on different platforms: * **JRuby**, **Windows**: server sockets are not seamless on restart, they must be closed and reopened. These platforms have no way to pass descriptors into a new process that is exposed to ruby * **JRuby**, **Windows**: cluster mode is not supported due to a lack of fork(2) * **Windows**: daemon mode is not supported due to a lack of fork(2) ## pumactl `pumactl` is a simple CLI frontend to the control/status app described above. Please refer to `pumactl --help` for available commands. ## Managing multiple Pumas / init.d / upstart scripts If you want an easy way to manage multiple scripts at once check [tools/jungle](https://github.com/puma/puma/tree/master/tools/jungle) for init.d and upstart scripts. ## Capistrano deployment Puma has support for Capistrano3 with an [external gem](https://github.com/seuros/capistrano-puma), you just need require that in Gemfile: ```ruby gem 'capistrano3-puma' ``` And then execute: ```bash bundle ``` Then add to Capfile ```ruby require 'capistrano/puma' ``` and then ```bash $ bundle exec cap puma:start $ bundle exec cap puma:restart $ bundle exec cap puma:stop $ bundle exec cap puma:phased_restart ``` ## Contributing To run the test suite: ```bash $ bundle install $ bundle exec rake ``` ## License Puma is copyright 2014 Evan Phoenix and contributors. It is licensed under the BSD 3-Clause license. See the include LICENSE file for details.
mit
lydell/babel
test/fixtures/transformation/api/blacklist/expected.js
264
"use strict"; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var Test = function Test() { _classCallCheck(this, Test); arr.map(x => x * x); };
mit
fhijaz/Graphite
tests/unit/cond/cond_test.c
3070
/**************************************************** * This is a test that will test condition variables* ****************************************************/ #include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #include "capi.h" #include "mcp_api.h" #include "sync_api.h" carbon_mutex_t my_mux; carbon_cond_t my_cond; #ifdef DEBUG pthread_mutex_t lock; #endif // Functions executed by threads void* test_wait_cond(void * threadid); void* test_signal_cond(void * threadid); int main(int argc, char* argv[]) // main begins { CarbonStartSim(); // Read in the command line arguments const unsigned int numThreads = 2; // Declare threads and related variables pthread_t threads[numThreads]; pthread_attr_t attr; #ifdef DEBUG printf("This is the function main()\n"); #endif // Initialize threads and related variables pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); #ifdef DEBUG printf("Spawning threads\n"); #endif pthread_create(&threads[0], &attr, test_wait_cond, (void *) 0); pthread_create(&threads[1], &attr, test_signal_cond, (void *) 1); // Wait for all threads to complete for (unsigned int i = 0; i < numThreads; i++) pthread_join(threads[i], NULL); printf("quitting syscall server!\n"); quitMCP(); #ifdef DEBUG printf("This is the function main ending\n"); #endif pthread_exit(NULL); CarbonStopSim(); } // main ends int wait_some() { int j = 0; for (unsigned int i = 0; i < 200000; i++) { j += i; } return j; } void* test_signal_cond(void *threadid) { usleep(500000); // Declare local variables int tid; CAPI_return_t rtnVal; rtnVal = CAPI_Initialize((int)threadid); // Initialize local variables CAPI_rank(&tid); // Make sure that the signal comes after the wait wait_some(); // Thread starts here fprintf(stderr, "UserSignal: Cond Signaling."); CarbonCondSignal(&my_cond); fprintf(stderr, "UserSignal: Cond Signaled."); CarbonMutexLock(&my_mux); fprintf(stderr, "UserSignal: Mutex locked after signal."); CarbonMutexUnlock(&my_mux); fprintf(stderr, "UserSignal: Signal thread done."); pthread_exit(NULL); } void* test_wait_cond(void *threadid) { // Declare local variables int tid; CAPI_return_t rtnVal; rtnVal = CAPI_Initialize((int)threadid); // Initialize local variables CAPI_rank(&tid); // Thread starts here // FIXME: This should be in the main thread or something. fprintf(stderr, "UserWait: Initting mutex."); CarbonMutexInit(&my_mux); fprintf(stderr, "UserWait: Initting cond."); CarbonCondInit(&my_cond); fprintf(stderr, "UserWait: Locking mux."); CarbonMutexLock(&my_mux); fprintf(stderr, "UserWait: Cond wait."); CarbonCondWait(&my_cond, &my_mux); fprintf(stderr, "UserWait: Cond done."); CarbonMutexUnlock(&my_mux); fprintf(stderr, "UserWait: test_wait_cond mutex unlock done."); pthread_exit(NULL); }
mit
cdnjs/cdnjs
ajax/libs/simple-icons/1.9.9/logstash.min.js
369
module.exports={title:"Logstash",hex:"005571",source:"https://www.elastic.co/brand",svg:'<svg aria-labelledby="simpleicons-logstash-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title id="simpleicons-logstash-icon">Logstash icon</title><path d="M12.6 7.2V24c-5.2 0-10.8-4-10.8-9.3V0h3.6c3.8 0 7.2 3.4 7.2 7.2zm2.4 6V24h7.2V13.2z"/></svg>\n'};
mit
cdnjs/cdnjs
ajax/libs/ckeditor/4.17.2/plugins/imagebase/lang/en-au.min.js
89
CKEDITOR.plugins.setLang("imagebase","en-au",{captionPlaceholder:"Enter image caption"});
mit
cdnjs/cdnjs
ajax/libs/deeplearn/0.6.0-alpha6/contrib/data/datasource.js
205
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DataSource = (function () { function DataSource() { } return DataSource; }()); exports.DataSource = DataSource;
mit
NounVannakGitHub/Java-Tutorial-Vollegen
MultiLanguage/src/multilanguage/ApplicationActionBarAdvisor.java
1642
package multilanguage; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; /** * An action bar advisor is responsible for creating, adding, and disposing of * the actions added to a workbench window. Each window will be populated with * new actions. */ public class ApplicationActionBarAdvisor extends ActionBarAdvisor { // Actions - important to allocate these only in makeActions, and then use // them // in the fill methods. This ensures that the actions aren't recreated // when fillActionBars is called with FILL_PROXY. private IWorkbenchAction exitAction; public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } protected void makeActions(final IWorkbenchWindow window) { // Creates the actions and registers them. // Registering is needed to ensure that key bindings work. // The corresponding commands keybindings are defined in the plugin.xml // file. // Registering also provides automatic disposal of the actions when // the window is closed. exitAction = ActionFactory.QUIT.create(window); register(exitAction); } protected void fillMenuBar(IMenuManager menuBar) { MenuManager fileMenu = new MenuManager("&File", IWorkbenchActionConstants.M_FILE); menuBar.add(fileMenu); fileMenu.add(exitAction); } }
epl-1.0
sleekmason/LG-V510-Kitkat
arch/arm/mach-pxa/include/mach/trizeps4.h
5077
/************************************************************************ * Include file for TRIZEPS4 SoM and ConXS eval-board * Copyright (c) Jürgen Schindele * 2006 ************************************************************************/ /* */ #ifndef _TRIPEPS4_H_ #define _TRIPEPS4_H_ /* */ #define TRIZEPS4_FLASH_PHYS (PXA_CS0_PHYS) /* */ #define TRIZEPS4_DISK_PHYS (PXA_CS1_PHYS) /* */ #define TRIZEPS4_ETH_PHYS (PXA_CS2_PHYS) /* */ #define TRIZEPS4_PIC_PHYS (PXA_CS3_PHYS) /* */ #define TRIZEPS4_SDRAM_BASE 0xa0000000 /* */ /* */ #define TRIZEPS4_CFSR_PHYS (PXA_CS3_PHYS) /* */ #define TRIZEPS4_BOCR_PHYS (PXA_CS3_PHYS+0x02000000) /* */ #define TRIZEPS4_IRCR_PHYS (PXA_CS3_PHYS+0x02400000) /* */ #define TRIZEPS4_UPSR_PHYS (PXA_CS3_PHYS+0x02800000) /* */ #define TRIZEPS4_DICR_PHYS (PXA_CS3_PHYS+0x03800000) /* */ #define TRIZEPS4_DISK_VIRT 0xF0000000 /* */ #define TRIZEPS4_PIC_VIRT 0xF0100000 /* */ #define TRIZEPS4_CFSR_VIRT 0xF0100000 #define TRIZEPS4_BOCR_VIRT 0xF0200000 #define TRIZEPS4_DICR_VIRT 0xF0300000 #define TRIZEPS4_IRCR_VIRT 0xF0400000 #define TRIZEPS4_UPSR_VIRT 0xF0500000 /* */ #define TRIZEPS4_FLASH_SIZE 0x02000000 /* */ /* */ #define GPIO_DM9000 101 #define TRIZEPS4_ETH_IRQ PXA_GPIO_TO_IRQ(GPIO_DM9000) /* */ #define GPIO_UCB1400 1 #define TRIZEPS4_UCB1400_IRQ PXA_GPIO_TO_IRQ(GPIO_UCB1400) /* */ #define GPIO_PCD 11 /* */ #define TRIZEPS4_CD_IRQ PXA_GPIO_TO_IRQ(GPIO_PCD) #define GPIO_PRDY 13 /* */ #define TRIZEPS4_READY_NINT PXA_GPIO_TO_IRQ(GPIO_PRDY) /* */ #define GPIO_MMC_DET 12 #define TRIZEPS4_MMC_IRQ PXA_GPIO_TO_IRQ(GPIO_MMC_DET) /* */ #define GPIO_DOC_LOCK 94 #define GPIO_DOC_IRQ 93 #define TRIZEPS4_DOC_IRQ PXA_GPIO_TO_IRQ(GPIO_DOC_IRQ) /* */ #define GPIO_SPI 53 #define TRIZEPS4_SPI_IRQ PXA_GPIO_TO_IRQ(GPIO_SPI) /* */ #define GPIO_SYS_BUSY_LED 46 #define GPIO_HEARTBEAT_LED 47 /* */ #define GPIO_PIC 0 #define TRIZEPS4_PIC_IRQ PXA_GPIO_TO_IRQ(GPIO_PIC) #ifdef CONFIG_MACH_TRIZEPS_CONXS /* */ #define CFSR_P2V(x) ((x) - TRIZEPS4_CFSR_PHYS + TRIZEPS4_CFSR_VIRT) #define CFSR_V2P(x) ((x) - TRIZEPS4_CFSR_VIRT + TRIZEPS4_CFSR_PHYS) #define BCR_P2V(x) ((x) - TRIZEPS4_BOCR_PHYS + TRIZEPS4_BOCR_VIRT) #define BCR_V2P(x) ((x) - TRIZEPS4_BOCR_VIRT + TRIZEPS4_BOCR_PHYS) #define DCR_P2V(x) ((x) - TRIZEPS4_DICR_PHYS + TRIZEPS4_DICR_VIRT) #define DCR_V2P(x) ((x) - TRIZEPS4_DICR_VIRT + TRIZEPS4_DICR_PHYS) #define IRCR_P2V(x) ((x) - TRIZEPS4_IRCR_PHYS + TRIZEPS4_IRCR_VIRT) #define IRCR_V2P(x) ((x) - TRIZEPS4_IRCR_VIRT + TRIZEPS4_IRCR_PHYS) #ifndef __ASSEMBLY__ static inline unsigned short CFSR_readw(void) { /* */ return *((unsigned short *)CFSR_P2V(0x0C000000)); } static inline void BCR_writew(unsigned short value) { /* */ *((unsigned short *)BCR_P2V(0x0E000000)) = value; } static inline void DCR_writew(unsigned short value) { /* */ *((unsigned short *)DCR_P2V(0x0E000000)) = value; } static inline void IRCR_writew(unsigned short value) { /* */ *((unsigned short *)IRCR_P2V(0x0E000000)) = value; } #else #define ConXS_CFSR CFSR_P2V(0x0C000000) #define ConXS_BCR BCR_P2V(0x0E000000) #define ConXS_DCR DCR_P2V(0x0F800000) #define ConXS_IRCR IRCR_P2V(0x0F800000) #endif #else /* */ static inline unsigned short CFSR_readw(void) { return 0; } static inline void BCR_writew(unsigned short value) { ; } static inline void DCR_writew(unsigned short value) { ; } static inline void IRCR_writew(unsigned short value) { ; } #endif /* */ #define ConXS_CFSR_BVD_MASK 0x0003 #define ConXS_CFSR_BVD1 (1 << 0) #define ConXS_CFSR_BVD2 (1 << 1) #define ConXS_CFSR_VS_MASK 0x000C #define ConXS_CFSR_VS1 (1 << 2) #define ConXS_CFSR_VS2 (1 << 3) #define ConXS_CFSR_VS_5V (0x3 << 2) #define ConXS_CFSR_VS_3V3 0x0 #define ConXS_BCR_S0_POW_EN0 (1 << 0) #define ConXS_BCR_S0_POW_EN1 (1 << 1) #define ConXS_BCR_L_DISP (1 << 4) #define ConXS_BCR_CF_BUF_EN (1 << 5) #define ConXS_BCR_CF_RESET (1 << 7) #define ConXS_BCR_S0_VCC_3V3 0x1 #define ConXS_BCR_S0_VCC_5V0 0x2 #define ConXS_BCR_S0_VPP_12V 0x4 #define ConXS_BCR_S0_VPP_3V3 0x8 #define ConXS_IRCR_MODE (1 << 0) #define ConXS_IRCR_SD (1 << 1) #endif /* */
gpl-2.0
rimistri/mediatek
mt6732/mediatek/platform/mt6752/kernel/core/mt_clkmgr.c
117521
#include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/list.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <asm/uaccess.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/smp.h> #include <linux/earlysuspend.h> #include <linux/io.h> #include <mach/mt_typedefs.h> #include <mach/sync_write.h> #include <mach/mt_clkmgr.h> #include <mach/mt_dcm.h> #include <mach/mt_spm.h> #include <mach/mt_spm_mtcmos.h> #include <mach/mt_spm_sleep.h> #include <mach/mt_freqhopping.h> #include <mach/mt_gpufreq.h> #include <mach/irqs.h> //#include <mach/pmic_mt6325_sw.h> #ifdef CONFIG_OF #include <linux/of.h> #include <linux/of_address.h> #endif #ifdef MTK_SENSOR_HUB_SUPPORT #include <mach/md32_ipi.h> #include <mach/md32_helper.h> #endif #ifdef CONFIG_OF void __iomem *clk_apmixed_base; void __iomem *clk_cksys_base; void __iomem *clk_infracfg_ao_base; void __iomem *clk_audio_base; void __iomem *clk_mfgcfg_base; void __iomem *clk_mmsys_config_base; void __iomem *clk_imgsys_base; void __iomem *clk_vdec_gcon_base; void __iomem *clk_mjc_config_base; void __iomem *clk_venc_gcon_base; #endif //#define CLK_LOG_TOP //#define CLK_LOG //#define DISP_CLK_LOG //#define SYS_LOG //#define MUX_LOG_TOP #define MUX_LOG //#define PLL_LOG_TOP #define PLL_LOG //#define Bring_Up #define PLL_CLK_LINK /************************************************ ********** log debug ********** ************************************************/ #define USING_XLOG #ifdef USING_XLOG #include <linux/xlog.h> #define TAG "Power/clkmgr" #define clk_err(fmt, args...) \ xlog_printk(ANDROID_LOG_ERROR, TAG, fmt, ##args) #define clk_warn(fmt, args...) \ xlog_printk(ANDROID_LOG_WARN, TAG, fmt, ##args) #define clk_info(fmt, args...) \ xlog_printk(ANDROID_LOG_INFO, TAG, fmt, ##args) #define clk_dbg(fmt, args...) \ xlog_printk(ANDROID_LOG_DEBUG, TAG, fmt, ##args) #define clk_ver(fmt, args...) \ xlog_printk(ANDROID_LOG_VERBOSE, TAG, fmt, ##args) #else #define TAG "[Power/clkmgr] " #define clk_err(fmt, args...) \ printk(KERN_ERR TAG); \ printk(KERN_CONT fmt, ##args) #define clk_warn(fmt, args...) \ printk(KERN_WARNING TAG); \ printk(KERN_CONT fmt, ##args) #define clk_info(fmt, args...) \ printk(KERN_NOTICE TAG); \ printk(KERN_CONT fmt, ##args) #define clk_dbg(fmt, args...) \ printk(KERN_INFO TAG); \ printk(KERN_CONT fmt, ##args) #define clk_ver(fmt, args...) \ printk(KERN_DEBUG TAG); \ printk(KERN_CONT fmt, ##args) #endif /************************************************ ********** register access ********** ************************************************/ #define clk_readl(addr) \ DRV_Reg32(addr) #define clk_writel(addr, val) \ mt_reg_sync_writel(val, addr) #define clk_setl(addr, val) \ mt_reg_sync_writel(clk_readl(addr) | (val), addr) #define clk_clrl(addr, val) \ mt_reg_sync_writel(clk_readl(addr) & ~(val), addr) /************************************************ ********** struct definition ********** ************************************************/ //#define CONFIG_CLKMGR_STAT struct pll; struct pll_ops { int (*get_state)(struct pll *pll); //void (*change_mode)(int mode); void (*enable)(struct pll *pll); void (*disable)(struct pll *pll); void (*fsel)(struct pll *pll, unsigned int value); int (*dump_regs)(struct pll *pll, unsigned int *ptr); //unsigned int (*vco_calc)(struct pll *pll); int (*hp_enable)(struct pll *pll); int (*hp_disable)(struct pll *pll); }; struct pll { const char *name; int type; int mode; int feat; int state; unsigned int cnt; unsigned int en_mask; void __iomem *base_addr; void __iomem *pwr_addr; struct pll_ops *ops; unsigned int hp_id; int hp_switch; #ifdef CONFIG_CLKMGR_STAT struct list_head head; #endif }; struct subsys; struct subsys_ops { int (*enable)(struct subsys *sys); int (*disable)(struct subsys *sys); int (*get_state)(struct subsys *sys); int (*dump_regs)(struct subsys *sys, unsigned int *ptr); }; struct subsys { const char *name; int type; int force_on; unsigned int cnt; unsigned int state; unsigned int default_sta; unsigned int sta_mask; // mask in PWR_STATUS void __iomem *ctl_addr; //int (*pwr_ctrl)(int state); struct subsys_ops *ops; struct cg_grp *start; unsigned int nr_grps; struct clkmux *mux; #ifdef CONFIG_CLKMGR_STAT struct list_head head; #endif }; struct clkmux; struct clkmux_ops { void (*sel)(struct clkmux *mux, unsigned int clksrc); void (*enable)(struct clkmux *mux); void (*disable)(struct clkmux *mux); }; struct clkmux { const char *name; unsigned int cnt; void __iomem *base_addr; unsigned int sel_mask; unsigned int pdn_mask; unsigned int offset; unsigned int nr_inputs; unsigned int upd_mask; struct clkmux_ops *ops; // struct clkmux *parent; struct clkmux *siblings; struct pll *pll; #ifdef CONFIG_CLKMGR_STAT struct list_head head; #endif }; struct cg_grp; struct cg_grp_ops { int (*prepare)(struct cg_grp *grp); int (*finished)(struct cg_grp *grp); unsigned int (*get_state)(struct cg_grp *grp); int (*dump_regs)(struct cg_grp *grp, unsigned int *ptr); }; struct cg_grp { const char *name; void __iomem *set_addr; void __iomem *clr_addr; void __iomem *sta_addr; void __iomem *dummy_addr; void __iomem *bw_limit_addr; unsigned int mask; unsigned int state; struct cg_grp_ops *ops; struct subsys *sys; }; struct cg_clk; struct cg_clk_ops { int (*get_state)(struct cg_clk *clk); int (*check_validity)(struct cg_clk *clk);// 1: valid, 0: invalid int (*enable)(struct cg_clk *clk); int (*disable)(struct cg_clk *clk); }; struct cg_clk { int cnt; unsigned int state; unsigned int mask; int force_on; struct cg_clk_ops *ops; struct cg_grp *grp; struct clkmux *mux; // struct cg_clk *parent; #ifdef CONFIG_CLKMGR_STAT struct list_head head; #endif }; #ifdef CONFIG_CLKMGR_STAT struct stat_node { struct list_head link; unsigned int cnt_on; unsigned int cnt_off; char name[0]; }; #endif /************************************************ ********** global variablies ********** ************************************************/ #define PWR_DOWN 0 #define PWR_ON 1 static int initialized = 0; static int es_flag = 0; static struct pll plls[NR_PLLS]; static struct subsys syss[NR_SYSS]; static struct clkmux muxs[NR_MUXS]; static struct cg_grp grps[NR_GRPS]; static struct cg_clk clks[NR_CLKS]; /************************************************ ********** spin lock protect ********** ************************************************/ static DEFINE_SPINLOCK(clock_lock); #define clkmgr_lock(flags) \ do { \ spin_lock_irqsave(&clock_lock, flags); \ } while (0) #define clkmgr_unlock(flags) \ do { \ spin_unlock_irqrestore(&clock_lock, flags); \ } while (0) #define clkmgr_locked() (spin_is_locked(&clock_lock)) int clkmgr_is_locked() { return clkmgr_locked(); } EXPORT_SYMBOL(clkmgr_is_locked); /************************************************ ********** clkmgr stat debug ********** ************************************************/ #ifdef CONFIG_CLKMGR_STAT void update_stat_locked(struct list_head *head, char *name, int op) { struct list_head *pos = NULL; struct stat_node *node = NULL; int len = strlen(name); int new_node = 1; list_for_each(pos, head) { node = list_entry(pos, struct stat_node, link); if (!strncmp(node->name, name, len)) { new_node = 0; break; } } if (new_node) { node = NULL; node = kzalloc(sizeof(*node) + len + 1, GFP_ATOMIC); if (!node) { clk_err("[%s]: malloc stat node for %s fail\n", __func__, name); return; } else { memcpy(node->name, name, len); list_add_tail(&node->link, head); } } if (op) { node->cnt_on++; } else { node->cnt_off++; } } #endif /************************************************ ********** function declaration ********** ************************************************/ static int pll_enable_locked(struct pll *pll); static int pll_disable_locked(struct pll *pll); static int sys_enable_locked(struct subsys *sys); static int sys_disable_locked(struct subsys *sys, int force_off); static void mux_enable_locked(struct clkmux *mux); static void mux_disable_locked(struct clkmux *mux); static int clk_enable_locked(struct cg_clk *clk); static int clk_disable_locked(struct cg_clk *clk); static inline int pll_enable_internal(struct pll *pll, char *name) { int err; err = pll_enable_locked(pll); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&pll->head, name, 1); #endif return err; } static inline int pll_disable_internal(struct pll *pll, char *name) { int err; err = pll_disable_locked(pll); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&pll->head, name, 0); #endif return err; } static inline int subsys_enable_internal(struct subsys *sys, char *name) { int err; err = sys_enable_locked(sys); #ifdef CONFIG_CLKMGR_STAT //update_stat_locked(&sys->head, name, 1); #endif return err; } static inline int subsys_disable_internal(struct subsys *sys, int force_off, char *name) { int err; err = sys_disable_locked(sys, force_off); #ifdef CONFIG_CLKMGR_STAT //update_stat_locked(&sys->head, name, 0); #endif return err; } static inline void mux_enable_internal(struct clkmux *mux, char *name) { mux_enable_locked(mux); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&mux->head, name, 1); #endif } static inline void mux_disable_internal(struct clkmux *mux, char *name) { mux_disable_locked(mux); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&mux->head, name, 0); #endif } static inline int clk_enable_internal(struct cg_clk *clk, char *name) { int err; err = clk_enable_locked(clk); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&clk->head, name, 1); #endif return err; } static inline int clk_disable_internal(struct cg_clk *clk, char *name) { int err; err = clk_disable_locked(clk); #ifdef CONFIG_CLKMGR_STAT update_stat_locked(&clk->head, name, 0); #endif return err; } /************************************************ ********** pll part ********** ************************************************/ #define PLL_TYPE_SDM 0 #define PLL_TYPE_LC 1 #define HAVE_RST_BAR (0x1 << 0) #define HAVE_PLL_HP (0x1 << 1) #define HAVE_FIX_FRQ (0x1 << 2) #define Others (0x1 << 3) #define RST_BAR_MASK 0x1000000 static struct pll_ops arm_pll_ops; static struct pll_ops sdm_pll_ops; static struct pll plls[NR_PLLS] = { { .name = __stringify(ARMCA7PLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = ARMCA7PLL_CON0, // .pwr_addr = ARMCA7PLL_PWR_CON0, .ops = &arm_pll_ops, .hp_id = FH_ARMCA7_PLLID, .hp_switch = 1, }, { .name = __stringify(MAINPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP | HAVE_RST_BAR, .en_mask = 0xF0000101, // .base_addr = MAINPLL_CON0, // .pwr_addr = MAINPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_MAIN_PLLID, .hp_switch = 1, }, { .name = __stringify(MSDCPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = MSDCPLL_CON0, // .pwr_addr = MSDCPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_MSDC_PLLID, .hp_switch = 1, }, { .name = __stringify(UNIVPLL), .type = PLL_TYPE_SDM, .feat = HAVE_RST_BAR | HAVE_FIX_FRQ, .en_mask = 0xFE000001, // .base_addr = UNIVPLL_CON0, // .pwr_addr = UNIVPLL_PWR_CON0, .ops = &sdm_pll_ops, }, { .name = __stringify(MMPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = MMPLL_CON0, // .pwr_addr = MMPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_MM_PLLID, .hp_switch = 1, }, { .name = __stringify(VENCPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = VENCPLL_CON0, // .pwr_addr = VENCPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_VENC_PLLID, .hp_switch = 1, }, { .name = __stringify(TVDPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = TVDPLL_CON0, // .pwr_addr = TVDPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_TVD_PLLID, .hp_switch = 1, }, { .name = __stringify(MPLL), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = MPLL_CON0, // .pwr_addr = MPLL_PWR_CON0, .ops = &sdm_pll_ops, .hp_id = FH_M_PLLID, .hp_switch = 1, }, { .name = __stringify(APLL1), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = APLL1_CON0, // .pwr_addr = APLL1_PWR_CON0, .ops = &sdm_pll_ops, }, { .name = __stringify(APLL2), .type = PLL_TYPE_SDM, .feat = HAVE_PLL_HP, .en_mask = 0x00000001, // .base_addr = APLL2_CON0, // .pwr_addr = APLL2_PWR_CON0, .ops = &sdm_pll_ops, } }; static struct pll *id_to_pll(unsigned int id) { return id < NR_PLLS ? plls + id : NULL; } #define PLL_PWR_ON (0x1 << 0) #define PLL_ISO_EN (0x1 << 1) #define SDM_PLL_N_INFO_MASK 0x001FFFFF #define UNIV_SDM_PLL_N_INFO_MASK 0x001fc000 #define SDM_PLL_N_INFO_CHG 0x80000000 #define ARMPLL_POSDIV_MASK 0x07000000 static int pll_get_state_op(struct pll *pll) { return clk_readl(pll->base_addr) & 0x1; } static void sdm_pll_enable_op(struct pll *pll) { #ifdef PLL_LOG //clk_info("[%s]: pll->name=%s\n", __func__, pll->name); clk_dbg("[%s]: pll->name=%s\n", __func__, pll->name); #endif // if( pll->base_addr == UNIVPLL_CON0 /*|| pll->base_addr == VENCPLL_CON0*/) // { // printk("univpll return \n"); // return;//for debug // } clk_setl(pll->pwr_addr, PLL_PWR_ON); udelay(2); clk_clrl(pll->pwr_addr, PLL_ISO_EN); clk_setl(pll->base_addr, pll->en_mask); udelay(20); if (pll->feat & HAVE_RST_BAR) { clk_setl(pll->base_addr, RST_BAR_MASK); } } static void sdm_pll_disable_op(struct pll *pll) { #ifdef PLL_LOG //clk_info("[%s]: pll->name=%s\n", __func__, pll->name); clk_dbg("[%s]: pll->name=%s\n", __func__, pll->name); #endif // if( pll->base_addr == UNIVPLL_CON0 /*|| pll->base_addr == VENCPLL_CON0*/) // { // printk("univpll return \n"); // return;//for debug // } if (pll->feat & HAVE_RST_BAR) { clk_clrl(pll->base_addr, RST_BAR_MASK); } clk_clrl(pll->base_addr, 0x1); clk_setl(pll->pwr_addr, PLL_ISO_EN); clk_clrl(pll->pwr_addr, PLL_PWR_ON); } static void sdm_pll_fsel_op(struct pll *pll, unsigned int value) { unsigned int ctrl_value; ctrl_value = clk_readl(pll->base_addr + 4); if(pll->base_addr == UNIVPLL_CON0) { ctrl_value &= ~UNIV_SDM_PLL_N_INFO_MASK; ctrl_value |= value & UNIV_SDM_PLL_N_INFO_MASK; } else { ctrl_value &= ~SDM_PLL_N_INFO_MASK; ctrl_value |= value & SDM_PLL_N_INFO_MASK; } ctrl_value |= SDM_PLL_N_INFO_CHG; clk_writel(pll->base_addr + 4, ctrl_value); udelay(20); } static int sdm_pll_dump_regs_op(struct pll *pll, unsigned int *ptr) { *(ptr) = clk_readl(pll->base_addr); *(++ptr) = clk_readl(pll->base_addr + 4); *(++ptr) = clk_readl(pll->pwr_addr); return 3; } static int sdm_pll_hp_enable_op(struct pll *pll) { int err; if (!pll->hp_switch || (pll->state == PWR_DOWN)) { return 0; } #ifndef Bring_Up err = freqhopping_config(pll->hp_id, 0, PWR_ON); #endif return err; } static int sdm_pll_hp_disable_op(struct pll *pll) { int err; if (!pll->hp_switch || (pll->state == PWR_ON)) { return 0; } #ifndef Bring_Up err = freqhopping_config(pll->hp_id, 0, PWR_DOWN); #endif return err; } static struct pll_ops sdm_pll_ops = { .get_state = pll_get_state_op, .enable = sdm_pll_enable_op, .disable = sdm_pll_disable_op, .fsel = sdm_pll_fsel_op, .dump_regs = sdm_pll_dump_regs_op, .hp_enable = sdm_pll_hp_enable_op, .hp_disable = sdm_pll_hp_disable_op, }; static void arm_pll_fsel_op(struct pll *pll, unsigned int value) { unsigned int ctrl_value; ctrl_value = clk_readl(pll->base_addr + 4); ctrl_value &= ~(SDM_PLL_N_INFO_MASK | ARMPLL_POSDIV_MASK); ctrl_value |= value & (SDM_PLL_N_INFO_MASK | ARMPLL_POSDIV_MASK); ctrl_value |= SDM_PLL_N_INFO_CHG; clk_writel(pll->base_addr + 4, ctrl_value); udelay(20); } static struct pll_ops arm_pll_ops = { .get_state = pll_get_state_op, .enable = sdm_pll_enable_op, .disable = sdm_pll_disable_op, .fsel = arm_pll_fsel_op, .dump_regs = sdm_pll_dump_regs_op, .hp_enable = sdm_pll_hp_enable_op, .hp_disable = sdm_pll_hp_disable_op, }; static int get_pll_state_locked(struct pll *pll) { if (likely(initialized)) { return pll->state; } else { return pll->ops->get_state(pll); } } static int pll_enable_locked(struct pll *pll) { pll->cnt++; #ifdef PLL_LOG_TOP clk_info("[%s]: Start. pll->name=%s, pll->cnt=%d, pll->state=%d\n", __func__, pll->name, pll->cnt, pll->state); #endif if (pll->cnt > 1) { return 0; } if (pll->state == PWR_DOWN) { pll->ops->enable(pll); pll->state = PWR_ON; } if (pll->ops->hp_enable) { pll->ops->hp_enable(pll); } #ifdef PLL_LOG_TOP clk_info("[%s]: End. pll->name=%s, pll->cnt=%d, pll->state=%d\n", __func__, pll->name, pll->cnt, pll->state); #endif return 0; } static int pll_disable_locked(struct pll *pll) { #ifdef PLL_LOG_TOP clk_info("[%s]: Start. pll->name=%s, pll->cnt=%d, pll->state=%d\n", __func__, pll->name, pll->cnt, pll->state); #endif BUG_ON(!pll->cnt); pll->cnt--; #ifdef PLL_LOG_TOP clk_info("[%s]: Start. pll->name=%s, pll->cnt=%d, pll->state=%d\n", __func__, pll->name, pll->cnt, pll->state); #endif if (pll->cnt > 0) { return 0; } if (pll->state == PWR_ON) { pll->ops->disable(pll); pll->state = PWR_DOWN; } if (pll->ops->hp_disable) { pll->ops->hp_disable(pll); } #ifdef PLL_LOG_TOP clk_info("[%s]: End. pll->name=%s, pll->cnt=%d, pll->state=%d\n", __func__, pll->name, pll->cnt, pll->state); #endif return 0; } static int pll_fsel_locked(struct pll *pll, unsigned int value) { pll->ops->fsel(pll, value); if (pll->ops->hp_enable) { pll->ops->hp_enable(pll); } return 0; } int pll_is_on(int id) { int state; unsigned long flags; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!pll); clkmgr_lock(flags); state = get_pll_state_locked(pll); clkmgr_unlock(flags); return state; } EXPORT_SYMBOL(pll_is_on); int enable_pll(int id, char *name) { int err; unsigned long flags; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); BUG_ON(!name); #ifdef PLL_LOG_TOP clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); #endif clkmgr_lock(flags); err = pll_enable_internal(pll, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(enable_pll); int disable_pll(int id, char *name) { int err; unsigned long flags; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); BUG_ON(!name); #ifdef PLL_LOG_TOP clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); #endif clkmgr_lock(flags); err = pll_disable_internal(pll, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(disable_pll); int pll_fsel(int id, unsigned int value) { int err; unsigned long flags; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); clkmgr_lock(flags); err = pll_fsel_locked(pll, value); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(pll_fsel); int pll_hp_switch_on(int id, int hp_on) { int err = 0; unsigned long flags; int old_value; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); if (pll->type != PLL_TYPE_SDM) { err = -EINVAL; goto out; } clkmgr_lock(flags); old_value = pll->hp_switch; if (old_value == 0) { pll->hp_switch = 1; if (hp_on) { err = pll->ops->hp_enable(pll); } } clkmgr_unlock(flags); #if 0 clk_info("[%s]hp_switch(%d->%d), hp_on=%d\n", __func__, old_value, pll->hp_switch, hp_on); #endif out: return err; } EXPORT_SYMBOL(pll_hp_switch_on); int pll_hp_switch_off(int id, int hp_off) { int err = 0; unsigned long flags; int old_value; struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); if (pll->type != PLL_TYPE_SDM) { err = -EINVAL; goto out; } clkmgr_lock(flags); old_value = pll->hp_switch; if (old_value == 1) { if (hp_off) { err = pll->ops->hp_disable(pll); } pll->hp_switch = 0; } clkmgr_unlock(flags); #if 0 clk_info("[%s]hp_switch(%d->%d), hp_off=%d\n", __func__, old_value, pll->hp_switch, hp_off); #endif out: return err; } EXPORT_SYMBOL(pll_hp_switch_off); int pll_dump_regs(int id, unsigned int *ptr) { struct pll *pll = id_to_pll(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!pll); return pll->ops->dump_regs(pll, ptr); } EXPORT_SYMBOL(pll_dump_regs); const char* pll_get_name(int id) { struct pll *pll = id_to_pll(id); BUG_ON(!initialized); BUG_ON(!pll); return pll->name; } void set_mipi26m(int en) { unsigned long flags; #ifdef Bring_Up return; #endif clkmgr_lock(flags); if(en) clk_setl(AP_PLL_CON0, 1 << 6); else clk_clrl(AP_PLL_CON0, 1 << 6); clkmgr_unlock(flags); } EXPORT_SYMBOL(set_mipi26m); void set_ada_ssusb_xtal_ck(int en) { unsigned long flags; #ifdef Bring_Up return; #endif clkmgr_lock(flags); if(en) { clk_setl(AP_PLL_CON2, 1 << 0); udelay(100); clk_setl(AP_PLL_CON2, 1 << 1); clk_setl(AP_PLL_CON2, 1 << 2); } else { clk_clrl(AP_PLL_CON2, 0x7); } clkmgr_unlock(flags); } EXPORT_SYMBOL(set_ada_ssusb_xtal_ck); /************************************************ ********** subsys part ********** ************************************************/ #define SYS_TYPE_MODEM 0 #define SYS_TYPE_MEDIA 1 #define SYS_TYPE_OTHER 2 #define SYS_TYPE_CONN 3 static struct subsys_ops md1_sys_ops; static struct subsys_ops conn_sys_ops; static struct subsys_ops dis_sys_ops; static struct subsys_ops mfg_sys_ops; static struct subsys_ops isp_sys_ops; static struct subsys_ops vde_sys_ops; static struct subsys_ops mjc_sys_ops; static struct subsys_ops ven_sys_ops; static struct subsys_ops aud_sys_ops; static struct subsys_ops md2_sys_ops; static struct subsys syss[NR_SYSS] = { { .name = __stringify(SYS_MD1), .type = SYS_TYPE_MODEM, .default_sta = PWR_DOWN, .sta_mask = 1U << 0, // .ctl_addr = SPM_MD_PWR_CON, .ops = &md1_sys_ops, }, { .name = __stringify(SYS_MD2), .type = SYS_TYPE_MODEM, .default_sta = PWR_DOWN, .sta_mask = 1U << 27, // .ctl_addr = SPM_MD2_PWR_CON, .ops = &md2_sys_ops, }, { .name = __stringify(SYS_CONN), .type = SYS_TYPE_CONN, .default_sta = PWR_DOWN, .sta_mask = 1U << 1, // .ctl_addr = SPM_CONN_PWR_CON, .ops = &conn_sys_ops, }, { .name = __stringify(SYS_DIS), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 3, // .ctl_addr = SPM_DIS_PWR_CON, .ops = &dis_sys_ops, .start = &grps[CG_DISP0], .nr_grps = 2, .mux = &muxs[MT_MUX_MM], }, { .name = __stringify(SYS_MFG), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 4, // .ctl_addr = SPM_MFG_PWR_CON, .ops = &mfg_sys_ops, .start = &grps[CG_MFG], .nr_grps = 1, .mux = &muxs[MT_MUX_MFG], }, { .name = __stringify(SYS_ISP), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 5, // .ctl_addr = SPM_ISP_PWR_CON, .ops = &isp_sys_ops, .start = &grps[CG_IMAGE], .nr_grps = 1, //.mux = &muxs[MT_MUX_SCAM], }, { .name = __stringify(SYS_VDE), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 7, // .ctl_addr = SPM_VDE_PWR_CON, .ops = &vde_sys_ops, .start = &grps[CG_VDEC0], .nr_grps = 2, .mux = &muxs[MT_MUX_VDEC], }, { .name = __stringify(SYS_MJC), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 20, // .ctl_addr = SPM_MJC_PWR_CON, .ops = &mjc_sys_ops, .start = &grps[CG_MJC], .nr_grps = 1, .mux = &muxs[MT_MUX_MJC], }, { .name = __stringify(SYS_VEN), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 21, // .ctl_addr = SPM_VEN_PWR_CON, .ops = &ven_sys_ops, .start = &grps[CG_VENC], .nr_grps = 1, //.mux = &muxs[MT_MUX_VENC], }, { .name = __stringify(SYS_AUD), .type = SYS_TYPE_MEDIA, .default_sta = PWR_ON, .sta_mask = 1U << 24, // .ctl_addr = SPM_AUDIO_PWR_CON, .ops = &aud_sys_ops, .start = &grps[CG_AUDIO], .nr_grps = 1, .mux = &muxs[MT_MUX_AUDINTBUS], } }; static void larb_backup(int larb_idx); static void larb_restore(int larb_idx); static struct subsys *id_to_sys(unsigned int id) { return id < NR_SYSS ? syss + id : NULL; } static int md1_sys_enable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_mdsys1(STA_POWER_ON); return err; } static int md1_sys_disable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_mdsys1(STA_POWER_DOWN); return err; } static int md2_sys_enable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_mdsys2(STA_POWER_ON); return err; } static int md2_sys_disable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_mdsys2(STA_POWER_DOWN); return err; } static int conn_sys_enable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_connsys(STA_POWER_ON); return err; } static int conn_sys_disable_op(struct subsys *sys) { int err; err = spm_mtcmos_ctrl_connsys(STA_POWER_DOWN); return err; } static int dis_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_disp(STA_POWER_ON); clk_writel(MMSYS_DUMMY, 0xFFFFFFFF); larb_restore(MT_LARB_DISP); return err; } static int dis_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif larb_backup(MT_LARB_DISP); err = spm_mtcmos_ctrl_disp(STA_POWER_DOWN); return err; } static int mfg_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif // mt_gpufreq_voltage_enable_set(1); //return 0;//for debug err = spm_mtcmos_ctrl_mfg_ASYNC(STA_POWER_ON); err = spm_mtcmos_ctrl_mfg(STA_POWER_ON); return err; } static int mfg_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif //return 0;//for debug err = spm_mtcmos_ctrl_mfg(STA_POWER_DOWN); err = spm_mtcmos_ctrl_mfg_ASYNC(STA_POWER_DOWN); // mt_gpufreq_voltage_enable_set(0); return err; } static int isp_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_isp(STA_POWER_ON); larb_restore(MT_LARB_IMG); return err; } static int isp_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif larb_backup(MT_LARB_IMG); err = spm_mtcmos_ctrl_isp(STA_POWER_DOWN); return err; } static int vde_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_vdec(STA_POWER_ON); larb_restore(MT_LARB_VDEC); return err; } static int vde_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif larb_backup(MT_LARB_VDEC); err = spm_mtcmos_ctrl_vdec(STA_POWER_DOWN); return err; } static int mjc_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_mjc(STA_POWER_ON); larb_restore(MT_LARB_MJC); return err; } static int mjc_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif larb_backup(MT_LARB_MJC); err = spm_mtcmos_ctrl_mjc(STA_POWER_DOWN); return err; } static int ven_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_venc(STA_POWER_ON); larb_restore(MT_LARB_VENC); return err; } static int ven_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif larb_backup(MT_LARB_VENC); err = spm_mtcmos_ctrl_venc(STA_POWER_DOWN); return err; } static int aud_sys_enable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_aud(STA_POWER_ON); return err; } static int aud_sys_disable_op(struct subsys *sys) { int err; #ifdef SYS_LOG clk_info("[%s]: sys->name=%s\n", __func__, sys->name); #endif err = spm_mtcmos_ctrl_aud(STA_POWER_DOWN); return err; } static int sys_get_state_op(struct subsys *sys) { unsigned int sta = clk_readl(SPM_PWR_STATUS); unsigned int sta_s = clk_readl(SPM_PWR_STATUS_2ND); return (sta & sys->sta_mask) && (sta_s & sys->sta_mask); } static int sys_dump_regs_op(struct subsys *sys, unsigned int *ptr) { *(ptr) = clk_readl(sys->ctl_addr); return 1; } static struct subsys_ops md1_sys_ops = { .enable = md1_sys_enable_op, .disable = md1_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops conn_sys_ops = { .enable = conn_sys_enable_op, .disable = conn_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops dis_sys_ops = { .enable = dis_sys_enable_op, .disable = dis_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops mfg_sys_ops = { .enable = mfg_sys_enable_op, .disable = mfg_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops isp_sys_ops = { .enable = isp_sys_enable_op, .disable = isp_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops vde_sys_ops = { .enable = vde_sys_enable_op, .disable = vde_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops mjc_sys_ops = { .enable = mjc_sys_enable_op, .disable = mjc_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops ven_sys_ops = { .enable = ven_sys_enable_op, .disable = ven_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops aud_sys_ops = { .enable = aud_sys_enable_op, .disable = aud_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static struct subsys_ops md2_sys_ops = { .enable = md2_sys_enable_op, .disable = md2_sys_disable_op, .get_state = sys_get_state_op, .dump_regs = sys_dump_regs_op, }; static int get_sys_state_locked(struct subsys* sys) { if (likely(initialized)) { return sys->state; } else { return sys->ops->get_state(sys); } } int subsys_is_on(int id) { int state; unsigned long flags; struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!sys); clkmgr_lock(flags); state = get_sys_state_locked(sys); clkmgr_unlock(flags); return state; } EXPORT_SYMBOL(subsys_is_on); //#define STATE_CHECK_DEBUG static int sys_enable_locked(struct subsys *sys) { int err; int local_state = sys->state; //get_subsys_local_state(sys); #ifdef STATE_CHECK_DEBUG int reg_state = sys->ops->get_state(sys);//get_subsys_reg_state(sys); BUG_ON(local_state != reg_state); #endif #ifdef SYS_LOG clk_info("[%s]: Start. sys->name=%s, sys->state=%d\n", __func__, sys->name, sys->state); #endif if (local_state == PWR_ON) { return 0; } if (sys->mux) { mux_enable_internal(sys->mux, "sys"); } err = sys->ops->enable(sys); WARN_ON(err); if (!err) { sys->state = PWR_ON; } #ifdef SYS_LOG clk_info("[%s]: End. sys->name=%s, sys->state=%d\n", __func__, sys->name, sys->state); #endif return err; } static int sys_disable_locked(struct subsys *sys, int force_off) { int err; int local_state = sys->state;//get_subsys_local_state(sys); int i; struct cg_grp *grp; #ifdef STATE_CHECK_DEBUG int reg_state = sys->ops->get_state(sys);//get_subsys_reg_state(sys); BUG_ON(local_state != reg_state); #endif #ifdef SYS_LOG clk_info("[%s]: Start. sys->name=%s, sys->state=%d, force_off=%d\n", __func__, sys->name, sys->state, force_off); #endif if (!force_off) { //could be power off or not for (i = 0; i < sys->nr_grps; i++) { grp = sys->start + i; if (grp->state) { return 0; } } } if (local_state == PWR_DOWN) { return 0; } err = sys->ops->disable(sys); WARN_ON(err); if (!err) { sys->state = PWR_DOWN; } if (sys->mux) { mux_disable_internal(sys->mux, "sys"); } #ifdef SYS_LOG clk_info("[%s]: End. sys->name=%s, sys->state=%d, force_off=%d\n", __func__, sys->name, sys->state, force_off); #endif return err; } int enable_subsys(int id, char *name) { int err; unsigned long flags; struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); clkmgr_lock(flags); err = subsys_enable_internal(sys, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(enable_subsys); int disable_subsys(int id, char *name) { int err; unsigned long flags; struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); clkmgr_lock(flags); err = subsys_disable_internal(sys, 0, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(disable_subsys); int disable_subsys_force(int id, char *name) { int err; unsigned long flags; struct subsys *sys = id_to_sys(id); BUG_ON(!initialized); BUG_ON(!sys); clkmgr_lock(flags); err = subsys_disable_internal(sys, 1, name); clkmgr_unlock(flags); return err; } int subsys_dump_regs(int id, unsigned int *ptr) { struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); return sys->ops->dump_regs(sys, ptr); } EXPORT_SYMBOL(subsys_dump_regs); const char* subsys_get_name(int id) { struct subsys *sys = id_to_sys(id); BUG_ON(!initialized); BUG_ON(!sys); return sys->name; } #define JIFFIES_PER_LOOP 10 int md_power_on(int id) { int err=0; unsigned long flags; struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); BUG_ON(sys->type != SYS_TYPE_MODEM); clkmgr_lock(flags); err = subsys_enable_internal(sys, "md"); /* if(id == 0) spm_mtcmos_ctrl_mdsys1(STA_POWER_ON); else spm_mtcmos_ctrl_mdsys2(STA_POWER_ON); */ clkmgr_unlock(flags); clk_info("[%s]: id = %d\n", __func__, id); WARN_ON(err); return err; } EXPORT_SYMBOL(md_power_on); #ifndef Bring_Up static bool(*spm_md_sleep[])(void) = { spm_is_md1_sleep, spm_is_md2_sleep, }; #endif int md_power_off(int id, unsigned int timeout) { int err=0; int cnt; bool slept=1; unsigned long flags; struct subsys *sys = id_to_sys(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); BUG_ON(sys->type != SYS_TYPE_MODEM); // 0: not sleep, 1: sleep #ifndef Bring_Up slept = spm_md_sleep[id](); #endif cnt = (timeout + JIFFIES_PER_LOOP - 1) / JIFFIES_PER_LOOP; while (!slept && cnt--) { msleep(MSEC_PER_SEC / JIFFIES_PER_LOOP); #ifndef Bring_Up slept = spm_md_sleep[id](); #endif if (slept) { break; } } clkmgr_lock(flags); err = subsys_disable_internal(sys, 0, "md"); /* if(id == 0) spm_mtcmos_ctrl_mdsys1(STA_POWER_DOWN); else spm_mtcmos_ctrl_mdsys2(STA_POWER_DOWN); */ clkmgr_unlock(flags); clk_info("[%s]: id = %d\n", __func__, id); WARN_ON(err); return !slept; } EXPORT_SYMBOL(md_power_off); int conn_power_on(void) { int err=0; unsigned long flags; struct subsys *sys = id_to_sys(SYS_CONN); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); BUG_ON(sys->type != SYS_TYPE_CONN); clkmgr_lock(flags); //spm_mtcmos_ctrl_connsys(STA_POWER_ON); err = subsys_enable_internal(sys, "conn"); clkmgr_unlock(flags); clk_info("[%s]\n", __func__); WARN_ON(err); return err; } EXPORT_SYMBOL(conn_power_on); int conn_power_off(void) { int err=0; unsigned long flags; struct subsys *sys = id_to_sys(SYS_CONN); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!sys); BUG_ON(sys->type != SYS_TYPE_CONN); clkmgr_lock(flags); //spm_mtcmos_ctrl_connsys(STA_POWER_DOWN); err = subsys_disable_internal(sys, 0, "conn"); clkmgr_unlock(flags); clk_info("[%s]\n", __func__); WARN_ON(err); return err; } EXPORT_SYMBOL(conn_power_off); static DEFINE_MUTEX(larb_monitor_lock); static LIST_HEAD(larb_monitor_handlers); void register_larb_monitor(struct larb_monitor *handler) { struct list_head *pos; #ifdef Bring_Up return; #endif clk_info("register_larb_monitor\n"); mutex_lock(&larb_monitor_lock); list_for_each(pos, &larb_monitor_handlers) { struct larb_monitor *l; l = list_entry(pos, struct larb_monitor, link); if (l->level > handler->level) break; } list_add_tail(&handler->link, pos); mutex_unlock(&larb_monitor_lock); } EXPORT_SYMBOL(register_larb_monitor); void unregister_larb_monitor(struct larb_monitor *handler) { #ifdef Bring_Up return; #endif mutex_lock(&larb_monitor_lock); list_del(&handler->link); mutex_unlock(&larb_monitor_lock); } EXPORT_SYMBOL(unregister_larb_monitor); static void larb_clk_prepare(int larb_idx) { switch (larb_idx) { case MT_LARB_DISP: /* display */ clk_writel(DISP_CG_CLR0, 0x3); break; case MT_LARB_VDEC: /* vde */ clk_writel(LARB_CKEN_SET, 0x1); break; case MT_LARB_IMG: /* isp */ clk_writel(IMG_CG_CLR, 0x1); break; case MT_LARB_VENC: /* venc */ clk_writel(VENC_CG_SET, 0x11); break; case MT_LARB_MJC: /* mjc */ clk_writel(MJC_CG_CLR, 0x21); break; default: BUG(); } } static void larb_clk_finish(int larb_idx) { switch (larb_idx) { case MT_LARB_DISP: /* display */ clk_writel(DISP_CG_SET0, 0x3); break; case MT_LARB_VDEC: /* vde */ clk_writel(LARB_CKEN_CLR, 0x1); break; case MT_LARB_IMG: /* isp */ clk_writel(IMG_CG_SET, 0x1); break; case MT_LARB_VENC: /* venc */ clk_writel(VENC_CG_CLR, 0x11); break; case MT_LARB_MJC: /* mjc */ clk_writel(MJC_CG_SET, 0x21); break; default: BUG(); } } static void larb_backup(int larb_idx) { struct larb_monitor *pos; //clk_info("[%s]: start to backup larb%d\n", __func__, larb_idx); clk_dbg("[%s]: backup larb%d\n", __func__, larb_idx); larb_clk_prepare(larb_idx); list_for_each_entry(pos, &larb_monitor_handlers, link) { if (pos->backup != NULL) { //clk_info("[%s]: backup larb\n", __func__); pos->backup(pos, larb_idx); } } larb_clk_finish(larb_idx); } static void larb_restore(int larb_idx) { struct larb_monitor *pos; //clk_info("[%s]: start to restore larb%d\n", __func__, larb_idx); clk_dbg("[%s]: restore larb%d\n", __func__, larb_idx); larb_clk_prepare(larb_idx); list_for_each_entry(pos, &larb_monitor_handlers, link) { if (pos->restore != NULL) { //clk_info("[%s]: restore larb\n", __func__); pos->restore(pos, larb_idx); } } larb_clk_finish(larb_idx); } /************************************************ ********** clkmux part ********** ************************************************/ static struct clkmux_ops clkmux_ops; static struct clkmux_ops audio_clkmux_ops; //static struct clkmux_ops hd_audio_clkmux_ops; static struct clkmux muxs[NR_MUXS] = { { .name = __stringify(MUX_MM),//0 // .base_addr = CLK_CFG_0, .sel_mask = 0x03000000, .pdn_mask = 0x80000000, .upd_mask = 1<<3, .offset = 24, .nr_inputs = 4, .ops = &clkmux_ops, //.pll = &plls[VENCPLL], }, { .name = __stringify(MUX_DDRPHY),//1 // .base_addr = CLK_CFG_0, .sel_mask = 0x00010000, .pdn_mask = 0x00800000, .upd_mask = 1<<2, .offset = 16, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_MEM),//2 // .base_addr = CLK_CFG_0, .sel_mask = 0x00000300, .pdn_mask = 0x00008000, .upd_mask = 1<<1, .offset = 8, .nr_inputs = 3, .ops = &clkmux_ops, }, { .name = __stringify(MUX_AXI),//3 // .base_addr = CLK_CFG_0, .sel_mask = 0x00000001, .pdn_mask = 0x00000080, .upd_mask = 1<<0, .offset = 0, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_MFG),//4 // .base_addr = CLK_CFG_1, .sel_mask = 0x03000000, .pdn_mask = 0x80000000, .upd_mask = 1<<7, .offset = 24, .nr_inputs = 3, .ops = &clkmux_ops, .pll = &plls[MMPLL], }, { .name = __stringify(MUX_VDEC),//5 // .base_addr = CLK_CFG_1, .sel_mask = 0x00000300, .pdn_mask = 0x00008000, .upd_mask = 1<<5, .offset = 8, .nr_inputs = 4, .ops = &clkmux_ops, }, { .name = __stringify(MUX_PWM),//6 // .base_addr = CLK_CFG_1, .sel_mask = 0x00000003, .pdn_mask = 0x00000080, .upd_mask = 1<<4, .offset = 0, .nr_inputs = 3, .ops = &clkmux_ops, }, { .name = __stringify(MUX_SPI),//7 // .base_addr = CLK_CFG_2, .sel_mask = 0x00010000, .pdn_mask = 0x00800000, .upd_mask = 1<<10, .offset = 16, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_UART),//8 // .base_addr = CLK_CFG_2, .sel_mask = 0x00000100, .pdn_mask = 0x00008000, .upd_mask = 1<<9, .offset = 8, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_CAMTG),//9 // .base_addr = CLK_CFG_2, .sel_mask = 0x00000003, .pdn_mask = 0x00000080, .upd_mask = 1<<8, .offset = 0, .nr_inputs = 3, .ops = &clkmux_ops, .pll = &plls[UNIVPLL], }, { .name = __stringify(MUX_MSDC30_1),//10 // .base_addr = CLK_CFG_3, .sel_mask = 0x07000000, .pdn_mask = 0x80000000, .upd_mask = 1<<14, .offset = 24, .nr_inputs = 7, .ops = &clkmux_ops, .pll = &plls[MSDCPLL], }, { .name = __stringify(MUX_MSDC50_0),//11 // .base_addr = CLK_CFG_3, .sel_mask = 0x000F0000, .pdn_mask = 0x00800000, .upd_mask = 1<<13, .offset = 16, .nr_inputs = 9, .ops = &clkmux_ops, .siblings = &muxs[MT_MUX_MSDC50_0_hclk], .pll = &plls[MSDCPLL], }, { .name = __stringify(MUX_MSDC50_0_hclk),//12 // .base_addr = CLK_CFG_3, .sel_mask = 0x00000300, .pdn_mask = 0x00008000, .upd_mask = 1<<12, .offset = 8, .nr_inputs = 4, .ops = &clkmux_ops, }, { .name = __stringify(MUX_AUDINTBUS),//13 // .base_addr = CLK_CFG_4, .sel_mask = 0x03000000, .pdn_mask = 0x80000000, .upd_mask = 1<<18, .offset = 24, .nr_inputs = 3, .ops = &audio_clkmux_ops, .siblings = &muxs[MT_MUX_AUDIO], }, { .name = __stringify(MUX_AUDIO),//14 // .base_addr = CLK_CFG_4, .sel_mask = 0x00030000, .pdn_mask = 0x00800000, .upd_mask = 1<<17, .offset = 16, .nr_inputs = 4, .ops = &audio_clkmux_ops, }, { .name = __stringify(MUX_MSDC30_3),//15 // .base_addr = CLK_CFG_4, .sel_mask = 0x00000700, .pdn_mask = 0x00008000, .upd_mask = 1<<16, .offset = 8, .nr_inputs = 7, .ops = &clkmux_ops, .pll = &plls[MSDCPLL], }, { .name = __stringify(MUX_MSDC30_2),//16 // .base_addr = CLK_CFG_4, .sel_mask = 0x00000007, .pdn_mask = 0x00000080, .upd_mask = 1<<15, .offset = 0, .nr_inputs = 7, .ops = &clkmux_ops, .pll = &plls[MSDCPLL], }, { .name = __stringify(MUX_MJC),//17 // .base_addr = CLK_CFG_5, .sel_mask = 0x03000000, .pdn_mask = 0x80000000, .upd_mask = 1<<22, .offset = 24, .nr_inputs = 3, .ops = &clkmux_ops, .pll = &plls[UNIVPLL], }, { .name = __stringify(MUX_SCP),//18 // .base_addr = CLK_CFG_5, .sel_mask = 0x00000300, .pdn_mask = 0x00008000, .upd_mask = 1<<20, .offset = 8, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_PMICSPI),//19 // .base_addr = CLK_CFG_5, .sel_mask = 0x00000001, .pdn_mask = 0x00000080, .upd_mask = 1<<19, .offset = 0, .nr_inputs = 2, .ops = &clkmux_ops, }, { .name = __stringify(MUX_AUD2),//20 // .base_addr = CLK_CFG_6, .sel_mask = 0x01000000, .pdn_mask = 0x80000000, .upd_mask = 1<<26, .offset = 24, .nr_inputs = 2, .ops = &clkmux_ops, .pll = &plls[APLL2], }, { .name = __stringify(MUX_AUD1),//21 // .base_addr = CLK_CFG_6, .sel_mask = 0x00010000, .pdn_mask = 0x00800000, .upd_mask = 1<<25, .offset = 16, .nr_inputs = 2, .ops = &clkmux_ops, .pll = &plls[APLL1], }, { .name = __stringify(MUX_SCAM),//22 // .base_addr = CLK_CFG_6, .sel_mask = 0x00000100, .pdn_mask = 0x00008000, .upd_mask = 1<<24, .offset = 8, .nr_inputs = 2, .ops = &clkmux_ops, .pll = &plls[UNIVPLL], }, { .name = __stringify(MUX_DPI0),//23 // .base_addr = CLK_CFG_6, .sel_mask = 0x00000007, .pdn_mask = 0x00000080, .upd_mask = 1<<23, .offset = 0, .nr_inputs = 5, .ops = &clkmux_ops, .pll = &plls[TVDPLL], }, { .name = __stringify(MT_MUX_USB),//24 //.sel_mask = 0x00000007, //.pdn_mask = 0x00000080, //.upd_mask = 1<<23, //.offset = 0, //.nr_inputs = 5, //.ops = &clkmux_ops, .pll = &plls[UNIVPLL], } }; static struct clkmux *id_to_mux(unsigned int id) { return id < NR_MUXS ? muxs + id : NULL; } static void clkmux_sel_op(struct clkmux *mux, unsigned clksrc) { // volatile unsigned int reg; #ifdef MUX_LOG_TOP //clk_info("[%s]: mux->name=%s, clksrc=%d\n", __func__, mux->name, clksrc); clk_dbg("[%s]: mux->name=%s, clksrc=%d\n", __func__, mux->name, clksrc); #endif #if 0 reg = clk_readl(mux->base_addr); reg &= ~(mux->sel_mask); reg |= (clksrc << mux->offset) & mux->sel_mask; clk_writel(mux->base_addr, reg); clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #else clk_writel(mux->base_addr+8, mux->sel_mask); //clr clk_writel(mux->base_addr+4, (clksrc << mux->offset)); //set clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #endif } static void clkmux_enable_op(struct clkmux *mux) { #ifdef MUX_LOG //clk_info("[%s]: mux->name=%s\n", __func__, mux->name); clk_dbg("[%s]: mux->name=%s\n", __func__, mux->name); #endif #if 0 clk_clrl(mux->base_addr, mux->pdn_mask); clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #else clk_writel(mux->base_addr+8, mux->pdn_mask);//write clr reg clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #endif } static void clkmux_disable_op(struct clkmux *mux) { #ifdef MUX_LOG //clk_info("[%s]: mux->name=%s\n", __func__, mux->name); clk_dbg("[%s]: mux->name=%s\n", __func__, mux->name); #endif #if 0 clk_setl(mux->base_addr, mux->pdn_mask); clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #else clk_writel(mux->base_addr+4, mux->pdn_mask); //write set reg clk_writel(CLK_CFG_UPDATE, mux->upd_mask); #endif } static struct clkmux_ops clkmux_ops = { .sel = clkmux_sel_op, .enable = clkmux_enable_op, .disable = clkmux_disable_op, }; /* static struct clkmux_ops hd_audio_clkmux_ops = { .enable = clkmux_enable_op, .disable = clkmux_disable_op, };*/ static void audio_clkmux_enable_op(struct clkmux *mux) { #ifdef MUX_LOG //clk_info("[%s]: mux->name=%s\n", __func__, mux->name); clk_dbg("[%s]: mux->name=%s\n", __func__, mux->name); #endif clk_clrl(mux->base_addr, mux->pdn_mask); clk_writel(CLK_CFG_UPDATE, mux->upd_mask); }; static struct clkmux_ops audio_clkmux_ops = { .sel = clkmux_sel_op, .enable = audio_clkmux_enable_op, .disable = clkmux_disable_op, }; static void clkmux_sel_locked(struct clkmux *mux, unsigned int clksrc) { mux->ops->sel(mux, clksrc); } static void mux_enable_locked(struct clkmux *mux) { mux->cnt++; #ifdef MUX_LOG_TOP clk_info("[%s]: Start. mux->name=%s, mux->cnt=%d\n", __func__, mux->name, mux->cnt); #endif if (mux->cnt > 1) { return; } if (mux->pll) { pll_enable_internal(mux->pll, "mux"); } // if (mux->parent) { // mux_enable_internal(mux->parent, "mux_p"); // } if(mux->ops) { mux->ops->enable(mux); } if (mux->siblings) { mux_enable_internal(mux->siblings, "mux_s"); } #ifdef MUX_LOG_TOP clk_info("[%s]: End. mux->name=%s, mux->cnt=%d\n", __func__, mux->name, mux->cnt); #endif } static void mux_disable_locked(struct clkmux *mux) { #ifdef MUX_LOG_TOP clk_info("[%s]: Start. mux->name=%s, mux->cnt=%d\n", __func__, mux->name, mux->cnt); #endif BUG_ON(!mux->cnt); mux->cnt--; #ifdef MUX_LOG_TOP clk_info("[%s]: Start. mux->name=%s, mux->cnt=%d\n", __func__, mux->name, mux->cnt); #endif if (mux->cnt > 0) { return; } if(mux->ops) { mux->ops->disable(mux); } if (mux->siblings) { mux_disable_internal(mux->siblings, "mux_s"); } // if (mux->parent) { // mux_disable_internal(mux->siblings, "mux_p"); // } if (mux->pll) { pll_disable_internal(mux->pll, "mux"); } #ifdef MUX_LOG_TOP clk_info("[%s]: End. mux->name=%s, mux->cnt=%d\n", __func__, mux->name, mux->cnt); #endif } int clkmux_sel(int id, unsigned int clksrc, char *name) { unsigned long flags; struct clkmux *mux = id_to_mux(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!mux); BUG_ON(clksrc >= mux->nr_inputs); clkmgr_lock(flags); clkmux_sel_locked(mux, clksrc); clkmgr_unlock(flags); return 0; } EXPORT_SYMBOL(clkmux_sel); void enable_mux(int id, char *name) { unsigned long flags; struct clkmux *mux = id_to_mux(id); #ifdef Bring_Up return; #endif BUG_ON(!initialized); BUG_ON(!mux); BUG_ON(!name); #ifdef MUX_LOG_TOP clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); //#else // if(id == MT_MUX_MM) // clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); #endif clkmgr_lock(flags); mux_enable_internal(mux, name); clkmgr_unlock(flags); return; } EXPORT_SYMBOL(enable_mux); void disable_mux(int id, char *name) { unsigned long flags; struct clkmux *mux = id_to_mux(id); #ifdef Bring_Up return; #endif BUG_ON(!initialized); BUG_ON(!mux); BUG_ON(!name); #ifdef MUX_LOG_TOP clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); //#else // if(id == MT_MUX_MM) // clk_info("[%s]: id=%d, name=%s\n", __func__, id, name); #endif clkmgr_lock(flags); mux_disable_internal(mux, name); clkmgr_unlock(flags); return; } EXPORT_SYMBOL(disable_mux); /************************************************ ********** cg_grp part ********** ************************************************/ static struct cg_grp_ops general_cg_grp_ops; static struct cg_grp_ops disp0_cg_grp_ops; static struct cg_grp_ops vdec_cg_grp_ops; static struct cg_grp_ops venc_cg_grp_ops; static struct cg_grp grps[NR_GRPS] = { { .name = __stringify(CG_INFRA0), // .set_addr = INFRA_PDN_SET0, //disable // .clr_addr = INFRA_PDN_CLR0, //enable // .sta_addr = INFRA_PDN_STA0, .mask = 0xBFE73FFF, .ops = &general_cg_grp_ops, }, { .name = __stringify(CG_INFRA1), // .set_addr = INFRA_PDN_SET1, //disable // .clr_addr = INFRA_PDN_CLR1, //enable // .sta_addr = INFRA_PDN_STA1, .mask = 0x87D40DFF, .ops = &general_cg_grp_ops, }, { .name = __stringify(CG_DISP0), // .set_addr = DISP_CG_SET0, //disable // .clr_addr = DISP_CG_CLR0, //enable // .sta_addr = DISP_CG_CON0, // .dummy_addr = MMSYS_DUMMY, // .bw_limit_addr = SMI_LARB_BWL_EN_REG, .mask = 0xFFFFFFFF, .ops = &disp0_cg_grp_ops, .sys = &syss[SYS_DIS], }, { .name = __stringify(CG_DISP1), // .set_addr = DISP_CG_SET1, //disable // .clr_addr = DISP_CG_CLR1, //enable // .sta_addr = DISP_CG_CON1, .mask = 0x0000003F, .ops = &general_cg_grp_ops, .sys = &syss[SYS_DIS], }, { .name = __stringify(CG_IMAGE), // .set_addr = IMG_CG_SET, //disable // .clr_addr = IMG_CG_CLR, //enable // .sta_addr = IMG_CG_CON, .mask = 0x00000BE1, .ops = &general_cg_grp_ops, .sys = &syss[SYS_ISP], }, { .name = __stringify(CG_MFG), // .set_addr = MFG_CG_SET, //disable // .clr_addr = MFG_CG_CLR, //enable // .sta_addr = MFG_CG_CON, .mask = 0x00000001, .ops = &general_cg_grp_ops, .sys = &syss[SYS_MFG], }, { .name = __stringify(CG_AUDIO), // .sta_addr = AUDIO_TOP_CON0, .mask = 0x00C03C4, .ops = &general_cg_grp_ops, .sys = &syss[SYS_AUD], }, { .name = __stringify(CG_VDEC0), // .set_addr = VDEC_CKEN_CLR, //disable // .clr_addr = VDEC_CKEN_SET, //enable .mask = 0x00000001, .ops = &vdec_cg_grp_ops, .sys = &syss[SYS_VDE], }, { .name = __stringify(CG_VDEC1), // .set_addr = LARB_CKEN_CLR, //disable // .clr_addr = LARB_CKEN_SET, //enable .mask = 0x00000001, .ops = &vdec_cg_grp_ops, .sys = &syss[SYS_VDE], }, { .name = __stringify(CG_MJC), // .set_addr = MJC_CG_SET, //disable // .clr_addr = MJC_CG_CLR, //enable // .sta_addr = MJC_CG_CON, .mask = 0x0000002F, .ops = &general_cg_grp_ops, .sys = &syss[SYS_MJC], }, { .name = __stringify(CG_VENC), // .set_addr = VENC_CG_CLR, //disable // .clr_addr = VENC_CG_SET, //enable // .sta_addr = VENC_CG_CON, .mask = 0x00001111, .ops = &venc_cg_grp_ops, .sys = &syss[SYS_VEN], } }; static struct cg_grp *id_to_grp(unsigned int id) { return id < NR_GRPS ? grps + id : NULL; } static unsigned int general_grp_get_state_op(struct cg_grp *grp) { volatile unsigned int val; struct subsys *sys = grp->sys; if (sys && !sys->state) { return 0; } val = clk_readl(grp->sta_addr); val = (~val) & (grp->mask); return val; } static int general_grp_dump_regs_op(struct cg_grp *grp, unsigned int *ptr) { *(ptr) = clk_readl(grp->sta_addr); // *(ptr) = clk_readl(grp->sta_addr) & grp->mask; return 1; } static struct cg_grp_ops general_cg_grp_ops = { .get_state = general_grp_get_state_op, .dump_regs = general_grp_dump_regs_op, }; static unsigned int disp0_grp_get_state_op(struct cg_grp *grp) { volatile unsigned int val; struct subsys *sys = grp->sys; if (sys && !sys->state) { return 0; } val = clk_readl(grp->dummy_addr); val = (~val) & (grp->mask); return val; } static int disp0_grp_dump_regs_op(struct cg_grp *grp, unsigned int *ptr) { *(ptr) = clk_readl(grp->sta_addr); *(++ptr) = clk_readl(grp->dummy_addr); // *(++ptr) = clk_readl(grp->bw_limit_addr); return 2; } static struct cg_grp_ops disp0_cg_grp_ops = { .get_state = disp0_grp_get_state_op, .dump_regs = disp0_grp_dump_regs_op, }; static unsigned int vdec_grp_get_state_op(struct cg_grp *grp) { volatile unsigned int val = clk_readl(grp->set_addr); val &= grp->mask; return val; } static int vdec_grp_dump_regs_op(struct cg_grp *grp, unsigned int *ptr) { *(ptr) = clk_readl(grp->set_addr); *(++ptr) = clk_readl(grp->clr_addr); return 2; } static struct cg_grp_ops vdec_cg_grp_ops = { .get_state = vdec_grp_get_state_op, .dump_regs = vdec_grp_dump_regs_op, }; static unsigned int venc_grp_get_state_op(struct cg_grp *grp) { volatile unsigned int val = clk_readl(grp->sta_addr); val &= grp->mask; return val; } static int venc_grp_dump_regs_op(struct cg_grp *grp, unsigned int *ptr) { *(ptr) = clk_readl(grp->sta_addr); return 1; } static struct cg_grp_ops venc_cg_grp_ops = { .get_state = venc_grp_get_state_op, .dump_regs = venc_grp_dump_regs_op, }; /************************************************ ********** cg_clk part ********** ************************************************/ static struct cg_clk_ops general_cg_clk_ops; static struct cg_clk_ops infra1_cg_clk_ops; #if 0 static struct cg_clk_ops audio_cg_clk_ops; #endif static struct cg_clk_ops audsys_cg_clk_ops; // @audio sys static struct cg_clk_ops disp0_cg_clk_ops; static struct cg_clk_ops vdec_cg_clk_ops; static struct cg_clk_ops venc_cg_clk_ops; static struct cg_clk clks[NR_CLKS] = { [CG_INFRA0_FROM ... CG_INFRA0_TO] = { .cnt = 0, .ops = &general_cg_clk_ops, .grp = &grps[CG_INFRA0], }, [CG_INFRA1_FROM ... CG_INFRA1_TO] = { .cnt = 0, .ops = &infra1_cg_clk_ops, .grp = &grps[CG_INFRA1], }, [CG_DISP0_FROM ... CG_DISP0_TO] = { .cnt = 0, .ops = &disp0_cg_clk_ops, .grp = &grps[CG_DISP0], }, [CG_DISP1_FROM ... CG_DISP1_TO] = { .cnt = 0, .ops = &general_cg_clk_ops, .grp = &grps[CG_DISP1], }, [CG_IMAGE_FROM ... CG_IMAGE_TO] = { .cnt = 0, .ops = &general_cg_clk_ops, .grp = &grps[CG_IMAGE], }, [CG_MFG_FROM ... CG_MFG_TO] = { .cnt = 0, .ops = &general_cg_clk_ops, .grp = &grps[CG_MFG], }, [CG_AUDIO_FROM ... CG_AUDIO_TO] = { .cnt = 0, .ops = &audsys_cg_clk_ops, .grp = &grps[CG_AUDIO], }, [CG_VDEC0_FROM ... CG_VDEC0_TO] = { .cnt = 0, .ops = &vdec_cg_clk_ops, .grp = &grps[CG_VDEC0], }, [CG_VDEC1_FROM ... CG_VDEC1_TO] = { .cnt = 0, .ops = &vdec_cg_clk_ops, .grp = &grps[CG_VDEC1], }, [CG_MJC_FROM ... CG_MJC_TO] = { .cnt = 0, .ops = &general_cg_clk_ops, .grp = &grps[CG_MJC], }, [CG_VENC_FROM ... CG_VENC_TO] = { .cnt = 0, .ops = &venc_cg_clk_ops, .grp = &grps[CG_VENC], }, }; static struct cg_clk *id_to_clk(unsigned int id) { return id < NR_CLKS ? clks + id : NULL; } static int general_clk_get_state_op(struct cg_clk *clk) { struct subsys *sys = clk->grp->sys; if (sys && !sys->state) { return PWR_DOWN; } return (clk_readl(clk->grp->sta_addr) & (clk->mask)) ? PWR_DOWN : PWR_ON ; } static int general_clk_check_validity_op(struct cg_clk *clk) { int valid = 0; if (clk->mask & clk->grp->mask) { valid = 1; } return valid; } static int general_clk_enable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif clk_writel(clk->grp->clr_addr, clk->mask); return 0; } static int general_clk_disable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif clk_writel(clk->grp->set_addr, clk->mask); return 0; } static int infra1_clk_enable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif #ifdef MTK_SENSOR_HUB_SUPPORT unsigned int count = 1000, cnt; unsigned long apdma_flags; if (clk->mask == 0x40000) { apdma_spin_lock_irqsave(&apdma_flags); //clk_info("apdma on\n"); if(flag_md32_addr != 0) { //clk_info("apdma on 2\n"); do { if (get_md32_semaphore(SEMAPHORE_APDMA) == 1) break; } while(count--); if (count == 0) BUG(); cnt = readl((void __iomem *)(MD32_DTCM + flag_apmcu_addr)); cnt++; mt_reg_sync_writel(cnt, (MD32_DTCM + flag_apmcu_addr)); clk_writel(clk->grp->clr_addr, clk->mask); release_md32_semaphore(SEMAPHORE_APDMA); } else { apmcu_clk_init_count++; clk_writel(clk->grp->clr_addr, clk->mask); } apdma_spin_unlock_irqrestore(&apdma_flags); return 0; } #endif clk_writel(clk->grp->clr_addr, clk->mask); return 0; } static int infra1_clk_disable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif #ifdef MTK_SENSOR_HUB_SUPPORT unsigned int count = 1000, cnt; unsigned long apdma_flags; if (clk->mask == 0x40000) { apdma_spin_lock_irqsave(&apdma_flags); //clk_info("apdma off\n"); if(flag_md32_addr != 0) { //clk_info("apdma off 2\n"); do { if (get_md32_semaphore(SEMAPHORE_APDMA) == 1) break; } while(count--); if (count == 0) BUG(); cnt = readl((void __iomem *)(MD32_DTCM + flag_apmcu_addr)); cnt--; mt_reg_sync_writel(cnt, (MD32_DTCM + flag_apmcu_addr)); cnt = readl((void __iomem *)(MD32_DTCM + flag_md32_addr)); //if(*(volatile unsigned int*)flag_md32_addr == 0) if(cnt == 0) clk_writel(clk->grp->set_addr, clk->mask); release_md32_semaphore(SEMAPHORE_APDMA); } else { apmcu_clk_init_count--; clk_writel(clk->grp->set_addr, clk->mask); } apdma_spin_unlock_irqrestore(&apdma_flags); return 0; } #endif clk_writel(clk->grp->set_addr, clk->mask); return 0; } static struct cg_clk_ops general_cg_clk_ops = { .get_state = general_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = general_clk_enable_op, .disable = general_clk_disable_op, }; static struct cg_clk_ops infra1_cg_clk_ops = { .get_state = general_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = infra1_clk_enable_op, .disable = infra1_clk_disable_op, }; static int disp0_clk_get_state_op(struct cg_clk *clk) { struct subsys *sys = clk->grp->sys; if (sys && !sys->state) { return PWR_DOWN; } return (clk_readl(clk->grp->dummy_addr) & (clk->mask)) ? PWR_DOWN : PWR_ON ; } static int disp0_clk_enable_op(struct cg_clk *clk) { #ifdef DISP_CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif // clk_writel(clk->grp->clr_addr, clk->mask); clk_clrl(clk->grp->dummy_addr, clk->mask); if(clk->mask & 0x00600003) clk_writel(clk->grp->clr_addr, clk->mask); return 0; } static int disp0_clk_disable_op(struct cg_clk *clk) { #ifdef DISP_CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif // clk_writel(clk->grp->set_addr, clk->mask); clk_setl(clk->grp->dummy_addr, clk->mask); if(clk->mask & 0x00600003) clk_writel(clk->grp->set_addr, clk->mask); return 0; } static struct cg_clk_ops disp0_cg_clk_ops = { .get_state = disp0_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = disp0_clk_enable_op, .disable = disp0_clk_disable_op, }; #if 0 static int audio_clk_enable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif clk_writel(clk->grp->clr_addr, clk->mask); // clk_setl(TOPAXI_SI0_CTL, 1U << 7); //audio not from AXI return 0; } static int audio_clk_disable_op(struct cg_clk *clk) { #ifdef CLK_LOG clk_info("[%s]: clk->grp->name=%s, clk->mask=0x%x\n", __func__, clk->grp->name, clk->mask); #endif // clk_clrl(TOPAXI_SI0_CTL, 1U << 7); //audio not from AXI clk_writel(clk->grp->set_addr, clk->mask); return 0; } static struct cg_clk_ops audio_cg_clk_ops = { .get_state = general_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = audio_clk_enable_op, .disable = audio_clk_disable_op, }; #endif static int audsys_clk_enable_op(struct cg_clk *clk) { // clk_info("[%s]: CLK_CFG_2=0x%x, CLK_CFG_3=0x%x\n", __func__, clk_readl(CLK_CFG_2),clk_readl(CLK_CFG_3)); clk_clrl(clk->grp->sta_addr, clk->mask); return 0; } static int audsys_clk_disable_op(struct cg_clk *clk) { clk_setl(clk->grp->sta_addr, clk->mask); return 0; } static struct cg_clk_ops audsys_cg_clk_ops = { .get_state = general_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = audsys_clk_enable_op, .disable = audsys_clk_disable_op, }; static int vdec_clk_get_state_op(struct cg_clk *clk) { return (clk_readl(clk->grp->set_addr) & (clk->mask)) ? PWR_ON : PWR_DOWN; } static struct cg_clk_ops vdec_cg_clk_ops = { .get_state = vdec_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = general_clk_enable_op, .disable = general_clk_disable_op, }; static int venc_clk_get_state_op(struct cg_clk *clk) { return (clk_readl(clk->grp->sta_addr) & (clk->mask)) ? PWR_ON : PWR_DOWN; } static struct cg_clk_ops venc_cg_clk_ops = { .get_state = venc_clk_get_state_op, .check_validity = general_clk_check_validity_op, .enable = general_clk_enable_op, .disable = general_clk_disable_op, }; #ifdef PLL_CLK_LINK static int power_prepare_locked(struct cg_grp *grp) { int err = 0; if (grp->sys) { err = subsys_enable_internal(grp->sys, "clk"); } return err; } static int power_finish_locked(struct cg_grp *grp) { int err = 0; if (grp->sys) { err = subsys_disable_internal(grp->sys, 0, "clk"); } return err; } #endif static int clk_enable_locked(struct cg_clk *clk) { struct cg_grp *grp = clk->grp; unsigned int local_state; #ifdef STATE_CHECK_DEBUG unsigned int reg_state; #endif #ifdef PLL_CLK_LINK int err; #endif clk->cnt++; #ifdef CLK_LOG clk_info("[%s]: Start. grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); #endif if (clk->cnt > 1) { return 0; } local_state = clk->state; #ifdef STATE_CHECK_DEBUG reg_state = grp->ops->get_state(grp, clk); //BUG_ON(local_state != reg_state); #endif #ifdef PLL_CLK_LINK if (clk->mux) { mux_enable_internal(clk->mux, "clk"); } err = power_prepare_locked(grp); BUG_ON(err); #endif // if (clk->parent) { // clk_enable_internal(clk->parent, "clk"); // } if (local_state == PWR_ON) { return 0; } clk->ops->enable(clk); clk->state = PWR_ON; grp->state |= clk->mask; #ifdef CLK_LOG clk_info("[%s]: End. grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); #endif return 0; } static void clk_stat_bug(void); static int clk_disable_locked(struct cg_clk *clk) { struct cg_grp *grp = clk->grp; unsigned int local_state; #ifdef STATE_CHECK_DEBUG unsigned int reg_state; #endif #ifdef PLL_CLK_LINK int err; #endif #ifdef CLK_LOG clk_info("[%s]: Start. grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); #endif if(!clk->cnt) { clk_info("[%s]: grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); clk_stat_bug(); } BUG_ON(!clk->cnt); clk->cnt--; #ifdef CLK_LOG clk_info("[%s]: Start. grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); #endif if (clk->cnt > 0) { return 0; } local_state = clk->state; #ifdef STATE_CHECK_DEBUG reg_state = grp->ops->get_state(grp, clk); //BUG_ON(local_state != reg_state); #endif if (local_state == PWR_DOWN) { return 0; } if (clk->force_on) { return 0; } clk->ops->disable(clk); clk->state = PWR_DOWN; grp->state &= ~(clk->mask); // if (clk->parent) { // clk_disable_internal(clk->parent, "clk"); // } #ifdef PLL_CLK_LINK err = power_finish_locked(grp); BUG_ON(err); if (clk->mux) { mux_disable_internal(clk->mux, "clk"); } #endif #ifdef CLK_LOG clk_info("[%s]: End. grp->name=%s, grp->state=0x%x, clk->mask=0x%x, clk->cnt=%d, clk->state=%d\n", __func__, grp->name, grp->state, clk->mask, clk->cnt, clk->state); #endif return 0; } static int get_clk_state_locked(struct cg_clk *clk) { if (likely(initialized)) { return clk->state; } else { return clk->ops->get_state(clk); } } int mt_enable_clock(enum cg_clk_id id, char *name) { int err; unsigned long flags; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); BUG_ON(!name); #ifdef CLK_LOG_TOP clk_info("[%s]: id=%d, names=%s\n", __func__, id, name); #else if ((id == MT_CG_DISP0_SMI_COMMON)) clk_dbg("[%s]: id=%d, names=%s\n", __func__, id, name); #endif clkmgr_lock(flags); err = clk_enable_internal(clk, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(mt_enable_clock); int mt_disable_clock(enum cg_clk_id id, char *name) { int err; unsigned long flags; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); BUG_ON(!name); #ifdef CLK_LOG_TOP clk_info("[%s]: id=%d, names=%s\n", __func__, id, name); #else if (id == MT_CG_DISP0_SMI_COMMON) clk_dbg("[%s]: id=%d, names=%s\n", __func__, id, name); #endif clkmgr_lock(flags); err = clk_disable_internal(clk, name); clkmgr_unlock(flags); return err; } EXPORT_SYMBOL(mt_disable_clock); int enable_clock_ext_locked(int id, char *name) { int err; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); BUG_ON(!clkmgr_locked()); err = clk_enable_internal(clk, name); return err; } EXPORT_SYMBOL(enable_clock_ext_locked); int disable_clock_ext_locked(int id, char *name) { int err; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); BUG_ON(!clkmgr_locked()); err = clk_disable_internal(clk, name); return err; } EXPORT_SYMBOL(disable_clock_ext_locked); int clock_is_on(int id) { int state; unsigned long flags; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 1; #endif BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); clkmgr_lock(flags); state = get_clk_state_locked(clk); clkmgr_unlock(flags); return state; } EXPORT_SYMBOL(clock_is_on); static void clk_set_force_on_locked(struct cg_clk *clk) { clk->force_on = 1; } static void clk_clr_force_on_locked(struct cg_clk *clk) { clk->force_on = 0; } void clk_set_force_on(int id) { unsigned long flags; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); clkmgr_lock(flags); clk_set_force_on_locked(clk); clkmgr_unlock(flags); } EXPORT_SYMBOL(clk_set_force_on); void clk_clr_force_on(int id) { unsigned long flags; struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); clkmgr_lock(flags); clk_clr_force_on_locked(clk); clkmgr_unlock(flags); } EXPORT_SYMBOL(clk_clr_force_on); int clk_is_force_on(int id) { struct cg_clk *clk = id_to_clk(id); #ifdef Bring_Up return 0; #endif BUG_ON(!initialized); BUG_ON(!clk); BUG_ON(!clk->grp); BUG_ON(!clk->ops->check_validity(clk)); return clk->force_on; } int grp_dump_regs(int id, unsigned int *ptr) { struct cg_grp *grp = id_to_grp(id); #ifdef Bring_Up return 0; #endif //BUG_ON(!initialized); BUG_ON(!grp); return grp->ops->dump_regs(grp, ptr); } EXPORT_SYMBOL(grp_dump_regs); const char* grp_get_name(int id) { struct cg_grp *grp = id_to_grp(id); #ifdef Bring_Up return 0; #endif //BUG_ON(!initialized); BUG_ON(!grp); return grp->name; } void print_grp_regs(void) { int i; int cnt; unsigned int value[3]; const char *name; for (i = 0; i < NR_GRPS; i++) { name = grp_get_name(i); cnt = grp_dump_regs(i, value); if (cnt == 1) { clk_info("[%02d][%-8s]=[0x%08x]\n", i, name, value[0]); } else if (cnt == 2){ clk_info("[%02d][%-8s]=[0x%08x][0x%08x]\n", i, name, value[0], value[1]); } else { clk_info("[%02d][%-8s]=[0x%08x][0x%08x][0x%08x]\n", i, name, value[0], value[1], value[2]); } } } /************************************************ ********** initialization ********** ************************************************/ #if 0 static void subsys_all_force_on(void) { if (test_spm_gpu_power_on()) { spm_mtcmos_ctrl_mfg(STA_POWER_ON); } else { clk_warn("[%s]: not force to turn on MFG\n", __func__); } spm_mtcmos_ctrl_vdec(STA_POWER_ON); spm_mtcmos_ctrl_venc(STA_POWER_ON); } #endif #define INFRA0_CG 0xFFFFFFFF #define INFRA1_CG 0xFFFFFFFF #define AUD_CG 0x000C03C4 #define MFG_CG 0x00000001 #define DISP0_CG 0xFFFFFFFF #define DISP1_CG 0x0000003F #define IMG_CG 0x00000BE1 #define VDEC_CG 0x00000001 #define LARB_CG 0x00000001 #define VENC_CG 0x00001111 #define MJC_CG 0x0000002F #if 0 static void cg_all_force_on(void) { //INFRA CG clk_writel(INFRA_PDN_CLR0, INFRA0_CG); clk_writel(INFRA_PDN_CLR1, INFRA1_CG); //AUDIO clk_clrl(AUDIO_TOP_CON0, AUD_CG); //MFG clk_writel(MFG_CG_CLR, MFG_CG); //DISP clk_writel(DISP_CG_CLR0, DISP0_CG); clk_writel(DISP_CG_CLR1, DISP1_CG); clk_writel(MMSYS_DUMMY, 0); //ISP clk_writel(IMG_CG_CLR, IMG_CG); //VDE clk_writel(VDEC_CKEN_SET, VDEC_CG); clk_writel(LARB_CKEN_SET, LARB_CG); //VENC clk_writel(VENC_CG_SET, VENC_CG); //MJC clk_writel(MJC_CG_CLR, MJC_CG); } #endif static void cg_bootup_pdn(void) { //AUDIO clk_writel(AUDIO_TOP_CON0, AUD_CG); //INFRA CG clk_writel(INFRA_PDN_SET0, 0x8427B180); clk_writel(INFRA_PDN_SET1, 0x6f0876); //apdma default PDN //MFG clk_writel(MFG_CG_SET, MFG_CG); //DISP clk_writel(DISP_CG_SET0, 0xff9ffffc); //DCM enable // clk_writel(DISP_CG_SET1, 0x0000003F); // //ISP clk_writel(IMG_CG_SET, IMG_CG); //VDE clk_writel(VDEC_CKEN_CLR, VDEC_CG); clk_writel(LARB_CKEN_CLR, LARB_CG); //VENC clk_clrl(VENC_CG_CON, VENC_CG); //MJC clk_writel(MJC_CG_SET, MJC_CG); } static void mt_subsys_init(void) { int i; struct subsys *sys; syss[SYS_MD1].ctl_addr = SPM_MD_PWR_CON; syss[SYS_CONN].ctl_addr = SPM_CONN_PWR_CON; syss[SYS_DIS].ctl_addr = SPM_DIS_PWR_CON; syss[SYS_MFG].ctl_addr = SPM_MFG_PWR_CON; syss[SYS_ISP].ctl_addr = SPM_ISP_PWR_CON; syss[SYS_VDE].ctl_addr = SPM_VDE_PWR_CON; syss[SYS_MJC].ctl_addr = SPM_MJC_PWR_CON; syss[SYS_VEN].ctl_addr = SPM_VEN_PWR_CON; syss[SYS_AUD].ctl_addr = SPM_AUDIO_PWR_CON; syss[SYS_MD2].ctl_addr = SPM_MD2_PWR_CON; for (i = 0; i < NR_SYSS; i++) { sys = &syss[i]; sys->state = sys->ops->get_state(sys); if (sys->state != sys->default_sta) { clk_info("[%s]%s, change state: (%u->%u)\n", __func__, sys->name, sys->state, sys->default_sta); if (sys->default_sta == PWR_DOWN) { sys_disable_locked(sys, 1); } else { sys_enable_locked(sys); } } #ifdef CONFIG_CLKMGR_STAT INIT_LIST_HEAD(&sys->head); #endif } } static void mt_plls_init(void) { int i; struct pll *pll; plls[ARMCA7PLL].base_addr = ARMCA7PLL_CON0; plls[ARMCA7PLL].pwr_addr = ARMCA7PLL_PWR_CON0; plls[MAINPLL].base_addr = MAINPLL_CON0; plls[MAINPLL].pwr_addr = MAINPLL_PWR_CON0; plls[MSDCPLL].base_addr = MSDCPLL_CON0; plls[MSDCPLL].pwr_addr = MSDCPLL_PWR_CON0; plls[UNIVPLL].base_addr = UNIVPLL_CON0; plls[UNIVPLL].pwr_addr = UNIVPLL_PWR_CON0; plls[MMPLL].base_addr = MMPLL_CON0; plls[MMPLL].pwr_addr = MMPLL_PWR_CON0; plls[VENCPLL].base_addr = VENCPLL_CON0; plls[VENCPLL].pwr_addr = VENCPLL_PWR_CON0; plls[TVDPLL].base_addr = TVDPLL_CON0; plls[TVDPLL].pwr_addr = TVDPLL_PWR_CON0; plls[MPLL].base_addr = MPLL_CON0; plls[MPLL].pwr_addr = MPLL_PWR_CON0; plls[APLL1].base_addr = APLL1_CON0; plls[APLL1].pwr_addr = APLL1_PWR_CON0; plls[APLL2].base_addr = APLL2_CON0; plls[APLL2].pwr_addr = APLL2_PWR_CON0; for (i = 0; i < NR_PLLS; i++) { pll = &plls[i]; pll->state = pll->ops->get_state(pll); //clk_info("[%s]: pll->name=%s, pll->state=%d\n", __func__, pll->name, pll->state); #ifdef CONFIG_CLKMGR_STAT INIT_LIST_HEAD(&pll->head); #endif } plls[MMPLL].cnt = 1; //plls[VENCPLL].cnt = 1; plls[UNIVPLL].cnt = 1; } /* static void mt_plls_enable_hp(void) { int i; struct pll *pll; for (i = 0; i < NR_PLLS; i++) { pll = &plls[i]; if (pll->ops->hp_enable) { pll->ops->hp_enable(pll); } } } */ static void mt_muxs_init(void) { int i; struct clkmux *mux; muxs[MT_MUX_MM].base_addr = CLK_CFG_0; muxs[MT_MUX_DDRPHY].base_addr = CLK_CFG_0; muxs[MT_MUX_MEM].base_addr = CLK_CFG_0; muxs[MT_MUX_AXI].base_addr = CLK_CFG_0; muxs[MT_MUX_MFG].base_addr = CLK_CFG_1; muxs[MT_MUX_VDEC].base_addr = CLK_CFG_1; muxs[MT_MUX_PWM].base_addr = CLK_CFG_1; muxs[MT_MUX_SPI].base_addr = CLK_CFG_2; muxs[MT_MUX_UART].base_addr = CLK_CFG_2; muxs[MT_MUX_CAMTG].base_addr = CLK_CFG_2; muxs[MT_MUX_MSDC30_1].base_addr = CLK_CFG_3; muxs[MT_MUX_MSDC50_0].base_addr = CLK_CFG_3; muxs[MT_MUX_MSDC50_0_hclk].base_addr = CLK_CFG_3; muxs[MT_MUX_AUDINTBUS].base_addr = CLK_CFG_4; muxs[MT_MUX_AUDIO].base_addr = CLK_CFG_4; muxs[MT_MUX_MSDC30_3].base_addr = CLK_CFG_4; muxs[MT_MUX_MSDC30_2].base_addr = CLK_CFG_4; muxs[MT_MUX_MJC].base_addr = CLK_CFG_5; muxs[MT_MUX_SCP].base_addr = CLK_CFG_5; muxs[MT_MUX_PMICSPI].base_addr = CLK_CFG_5; muxs[MT_MUX_AUD2].base_addr = CLK_CFG_6; muxs[MT_MUX_AUD1].base_addr = CLK_CFG_6; muxs[MT_MUX_SCAM].base_addr = CLK_CFG_6; muxs[MT_MUX_DPI0].base_addr = CLK_CFG_6; for (i = 0; i < NR_MUXS; i++) { mux = &muxs[i]; #ifdef CONFIG_CLKMGR_STAT INIT_LIST_HEAD(&mux->head); #endif } muxs[MT_MUX_AUDINTBUS].cnt = 1; muxs[MT_MUX_AUDIO].cnt = 1; muxs[MT_MUX_MM].cnt = 1; muxs[MT_MUX_MFG].cnt = 1; muxs[MT_MUX_VDEC].cnt = 1; muxs[MT_MUX_MJC].cnt = 1; //clk_writel(CLK_CFG_0+4, 0x800000); //pdn ddrphycfg //clk_writel(CLK_CFG_5+4, 0x8000); //pdn scp clk_writel(CLK_CFG_6+4, 0x8000); //pdn scam clk_writel(CLK_CFG_UPDATE, 1<<24); } static void mt_clks_init(void) { int i, j; struct cg_grp *grp; struct cg_clk *clk; grps[CG_INFRA0].set_addr = INFRA_PDN_SET0; grps[CG_INFRA0].clr_addr = INFRA_PDN_CLR0; grps[CG_INFRA0].sta_addr = INFRA_PDN_STA0; grps[CG_INFRA1].set_addr = INFRA_PDN_SET1; grps[CG_INFRA1].clr_addr = INFRA_PDN_CLR1; grps[CG_INFRA1].sta_addr = INFRA_PDN_STA1; grps[CG_DISP0].set_addr = DISP_CG_SET0; grps[CG_DISP0].clr_addr = DISP_CG_CLR0; grps[CG_DISP0].sta_addr = DISP_CG_CON0; grps[CG_DISP0].dummy_addr = MMSYS_DUMMY, grps[CG_DISP1].set_addr = DISP_CG_SET1; grps[CG_DISP1].clr_addr = DISP_CG_CLR1; grps[CG_DISP1].sta_addr = DISP_CG_CON1; grps[CG_IMAGE].set_addr = IMG_CG_SET; grps[CG_IMAGE].clr_addr = IMG_CG_CLR; grps[CG_IMAGE].sta_addr = IMG_CG_CON; grps[CG_MFG].set_addr = MFG_CG_SET; grps[CG_MFG].clr_addr = MFG_CG_CLR; grps[CG_MFG].sta_addr = MFG_CG_CON; grps[CG_AUDIO].sta_addr = AUDIO_TOP_CON0; grps[CG_VDEC0].clr_addr = VDEC_CKEN_SET; grps[CG_VDEC0].set_addr = VDEC_CKEN_CLR; grps[CG_VDEC1].clr_addr = LARB_CKEN_SET; grps[CG_VDEC1].set_addr = LARB_CKEN_CLR; grps[CG_MJC].set_addr = MJC_CG_SET; grps[CG_MJC].clr_addr = MJC_CG_CLR; grps[CG_MJC].sta_addr = MJC_CG_CON; grps[CG_VENC].clr_addr = VENC_CG_SET; grps[CG_VENC].set_addr = VENC_CG_CLR; grps[CG_VENC].sta_addr = VENC_CG_CON; for (i = 0; i < NR_GRPS; i++) { grp = &grps[i]; grp->state = grp->ops->get_state(grp); //clk_info("[%s]: grps=%d\n", __func__, i); for (j = 0; j < 32; j++) { if (grp->mask & (1U << j)) { clk = &clks[i * 32 + j]; //clk->grp = grp; //clk->cnt = 0; clk->mask = 1U << j; clk->state = clk->ops->get_state(clk); //(grp->state & clk->mask) ? PWR_DOWN : PWR_ON; //clk_info("[%s]: clk=%d, clk->state=%d\n", __func__, j, clk->state); #ifdef CONFIG_CLKMGR_STAT INIT_LIST_HEAD(&clk->head); #endif } } } clks[MT_CG_INFRA_USB_MCU].mux = &muxs[MT_MUX_USB]; clks[MT_CG_INFRA_MSDC_0].mux = &muxs[MT_MUX_MSDC50_0]; clks[MT_CG_INFRA_MSDC_1].mux = &muxs[MT_MUX_MSDC30_1]; clks[MT_CG_INFRA_MSDC_2].mux = &muxs[MT_MUX_MSDC30_2]; clks[MT_CG_INFRA_MSDC_3].mux = &muxs[MT_MUX_MSDC30_3]; clks[MT_CG_INFRA_UART0].mux = &muxs[MT_MUX_UART]; clks[MT_CG_INFRA_UART1].mux = &muxs[MT_MUX_UART]; clks[MT_CG_INFRA_UART2].mux = &muxs[MT_MUX_UART]; clks[MT_CG_INFRA_UART3].mux = &muxs[MT_MUX_UART]; clks[MT_CG_INFRA_SPI].mux = &muxs[MT_MUX_SPI]; clks[MT_CG_IMAGE_SEN_TG].mux = &muxs[MT_MUX_CAMTG]; clks[MT_CG_DISP1_DISP_PWM_26M].mux = &muxs[MT_MUX_PWM]; clks[MT_CG_DISP1_DPI_PIXEL].mux = &muxs[MT_MUX_DPI0]; // Don't disable these clock until it's clk_clr_force_on() is called clk_set_force_on_locked(&clks[MT_CG_DISP0_SMI_LARB0]); clk_set_force_on_locked(&clks[MT_CG_DISP0_SMI_COMMON]); } //#endif //#ifndef Bring_Up void iomap(void); int mt_clkmgr_init(void) { iomap(); BUG_ON(initialized); /* spm_mtcmos_ctrl_vdec(STA_POWER_DOWN); spm_mtcmos_ctrl_venc(STA_POWER_DOWN); spm_mtcmos_ctrl_isp(STA_POWER_DOWN); spm_mtcmos_ctrl_aud(STA_POWER_DOWN); spm_mtcmos_ctrl_mfg(STA_POWER_DOWN); spm_mtcmos_ctrl_mfg_2D(STA_POWER_DOWN); spm_mtcmos_ctrl_mfg_ASYNC(STA_POWER_DOWN); spm_mtcmos_ctrl_mjc(STA_POWER_DOWN); spm_mtcmos_ctrl_vdec(STA_POWER_ON); spm_mtcmos_ctrl_venc(STA_POWER_ON); spm_mtcmos_ctrl_isp(STA_POWER_ON); spm_mtcmos_ctrl_aud(STA_POWER_ON); spm_mtcmos_ctrl_mfg_ASYNC(STA_POWER_ON); spm_mtcmos_ctrl_mfg_2D(STA_POWER_ON); spm_mtcmos_ctrl_mfg(STA_POWER_ON); spm_mtcmos_ctrl_mjc(STA_POWER_ON); */ // cg_all_force_on(); cg_bootup_pdn(); mt_plls_init(); mt_subsys_init(); mt_muxs_init(); mt_clks_init(); initialized = 1; mt_freqhopping_init(); print_grp_regs(); return 0; } #ifdef CONFIG_MTK_MMC extern void msdc_clk_status(int * status); #else void msdc_clk_status(int * status) { *status = 0; } #endif #define MFG_ASYNC_PWR_STA_MASK (0x1 << 23) #define VEN_PWR_STA_MASK (0x1 << 21) #define MJC_PWR_STA_MASK (0x1 << 20) #define VDE_PWR_STA_MASK (0x1 << 7) #define ISP_PWR_STA_MASK (0x1 << 5) #define MFG_PWR_STA_MASK (0x1 << 4) #define DIS_PWR_STA_MASK (0x1 << 3) bool clkmgr_idle_can_enter(unsigned int *condition_mask, unsigned int *block_mask, enum idle_mode mode) { int i,j; unsigned int sd_mask = 0; unsigned int cg_mask = 0; #if 1 unsigned int sta; #endif msdc_clk_status(&sd_mask); if (sd_mask) { block_mask[CG_INFRA1] |= sd_mask; return false; } for (i = CG_INFRA0; i < NR_GRPS; i++) { cg_mask = grps[i].state & condition_mask[i]; if (cg_mask) { for (j = CG_INFRA0; j < NR_GRPS; j++) { block_mask[j] = grps[j].state & condition_mask[j]; } //block_mask[i] |= cg_mask; return false; } } #if 1 sta = clk_readl(SPM_PWR_STATUS); if (mode == dpidle) { if (sta & (MFG_PWR_STA_MASK | ISP_PWR_STA_MASK | VDE_PWR_STA_MASK | MJC_PWR_STA_MASK | VEN_PWR_STA_MASK | DIS_PWR_STA_MASK)) return false; } else if (mode == soidle) { if (sta & (MFG_PWR_STA_MASK | ISP_PWR_STA_MASK | VDE_PWR_STA_MASK | MJC_PWR_STA_MASK | VEN_PWR_STA_MASK)) return false; } #endif return true; } /************************************************ ********** function debug ********** ************************************************/ static int pll_test_read(struct seq_file *m, void *v) { int i,j; int cnt; unsigned int value[3]; const char *name; seq_printf(m, "********** pll register dump **********\n"); for (i = 0; i < NR_PLLS; i++) { name = pll_get_name(i); cnt = pll_dump_regs(i, value); for (j = 0; j < cnt; j++) { seq_printf(m, "[%d][%-7s reg%d]=[0x%08x]\n", i, name, j, value[j]); } } seq_printf(m, "\n********** pll_test help **********\n"); seq_printf(m, "enable pll: echo enable id [mod_name] > /proc/clkmgr/pll_test\n"); seq_printf(m, "disable pll: echo disable id [mod_name] > /proc/clkmgr/pll_test\n"); return 0; } static int pll_test_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { char desc[32]; int len = 0; char cmd[10]; char mod_name[10]; int id; int err = 0; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%s %d %s", cmd, &id, mod_name) == 3) { if (!strcmp(cmd, "enable")) { err = enable_pll(id, mod_name); } else if (!strcmp(cmd, "disable")) { err = disable_pll(id, mod_name); } } else if (sscanf(desc, "%s %d", cmd, &id) == 2) { if (!strcmp(cmd, "enable")) { err = enable_pll(id, "pll_test"); } else if (!strcmp(cmd, "disable")) { err = disable_pll(id, "pll_test"); } } clk_info("[%s]%s pll %d: result is %d\n", __func__, cmd, id, err); return count; } static int pll_fsel_read(struct seq_file *m, void *v) { int i; int cnt; unsigned int value[3]; const char *name; for (i = 0; i < NR_PLLS; i++) { name = pll_get_name(i); if (pll_is_on(i)) { cnt = pll_dump_regs(i, value); if (cnt >= 2) { seq_printf(m, "[%d][%-7s]=[0x%08x%08x]\n", i, name, value[0], value[1]); } else { seq_printf(m, "[%d][%-7s]=[0x%08x]\n", i, name, value[0]); } } else { seq_printf(m, "[%d][%-7s]=[-1]\n", i, name); } } seq_printf(m, "\n********** pll_fsel help **********\n"); seq_printf(m, "adjust pll frequency: echo id freq > /proc/clkmgr/pll_fsel\n"); return 0; } static int pll_fsel_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { char desc[32]; int len = 0; int id; unsigned int value; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%d %x", &id, &value) == 2) { pll_fsel(id, value); } return count; } #ifdef CONFIG_CLKMGR_STAT static int pll_stat_read(struct seq_file *m, void *v) { struct pll *pll; struct list_head *pos; struct stat_node *node; int i; seq_printf(m, "\n********** pll stat dump **********\n"); for (i = 0; i < NR_PLLS; i++) { pll = id_to_pll(i); seq_printf(m, "[%d][%-7s]state=%u, cnt=%u", i, pll->name, pll->state, pll->cnt); list_for_each(pos, &pll->head) { node = list_entry(pos, struct stat_node, link); seq_printf(m, "\t(%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); } seq_printf(m, "\n"); } seq_printf(m, "\n********** pll_dump help **********\n"); return 0; } #endif static int subsys_test_read(struct seq_file *m, void *v) { int i; int state; unsigned int value=0, sta, sta_s; const char *name; sta = clk_readl(SPM_PWR_STATUS); sta_s = clk_readl(SPM_PWR_STATUS_2ND); seq_printf(m, "********** subsys register dump **********\n"); for (i = 0; i < NR_SYSS; i++) { name = subsys_get_name(i); state = subsys_is_on(i); subsys_dump_regs(i, &value); seq_printf(m, "[%d][%-7s]=[0x%08x], state(%u)\n", i, name, value, state); } seq_printf(m, "SPM_PWR_STATUS=0x%08x, SPM_PWR_STATUS_2ND=0x%08x\n", sta, sta_s); seq_printf(m, "\n********** subsys_test help **********\n"); seq_printf(m, "enable subsys: echo enable id > /proc/clkmgr/subsys_test\n"); seq_printf(m, "disable subsys: echo disable id [force_off] > /proc/clkmgr/subsys_test\n"); return 0; } static int subsys_test_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { char desc[32]; int len = 0; char cmd[10]; int id; int force_off; int err = 0; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%s %d %d", cmd, &id, &force_off) == 3) { if (!strcmp(cmd, "disable")) { err = disable_subsys_force(id, "test"); } } else if (sscanf(desc, "%s %d", cmd, &id) == 2) { if (!strcmp(cmd, "enable")) { err = enable_subsys(id, "test"); } else if (!strcmp(cmd, "disable")) { err = disable_subsys(id, "test"); } } clk_info("[%s]%s subsys %d: result is %d\n", __func__, cmd, id, err); return count; } #ifdef CONFIG_CLKMGR_STAT static int subsys_stat_read(struct seq_file *m, void *v) { struct subsys *sys; struct list_head *pos; struct stat_node *node; int i; seq_printf(m, "\n********** subsys stat dump **********\n"); for (i = 0; i < NR_SYSS; i++) { sys = id_to_sys(i); seq_printf(m, "[%d][%-7s]state=%u", i, sys->name, sys->state); list_for_each(pos, &sys->head) { node = list_entry(pos, struct stat_node, link); seq_printf(m, "\t(%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); } seq_printf(m, "\n"); } seq_printf(m, "\n********** subsys_dump help **********\n"); return 0; } #endif static int mux_test_read(struct seq_file *m, void *v) { seq_printf(m, "********** mux register dump *********\n"); seq_printf(m, "[CLK_CFG_0]=0x%08x\n", clk_readl(CLK_CFG_0)); seq_printf(m, "[CLK_CFG_1]=0x%08x\n", clk_readl(CLK_CFG_1)); seq_printf(m, "[CLK_CFG_2]=0x%08x\n", clk_readl(CLK_CFG_2)); seq_printf(m, "[CLK_CFG_3]=0x%08x\n", clk_readl(CLK_CFG_3)); seq_printf(m, "[CLK_CFG_4]=0x%08x\n", clk_readl(CLK_CFG_4)); seq_printf(m, "[CLK_CFG_5]=0x%08x\n", clk_readl(CLK_CFG_5)); seq_printf(m, "[CLK_CFG_6]=0x%08x\n", clk_readl(CLK_CFG_6)); seq_printf(m, "\n********** mux_test help *********\n"); return 0; } #ifdef CONFIG_CLKMGR_STAT static int mux_stat_read(struct seq_file *m, void *v) { struct clkmux *mux; struct list_head *pos; struct stat_node *node; int i; seq_printf(m, "********** mux stat dump **********\n"); for (i = 0; i < NR_MUXS; i++) { mux = id_to_mux(i); #if 0 seq_printf(m, "[%02d][%-14s]state=%u, cnt=%u", i, mux->name, mux->state, mux->cnt); #else seq_printf(m, "[%02d][%-14s]cnt=%u", i, mux->name, mux->cnt); #endif list_for_each(pos, &mux->head) { node = list_entry(pos, struct stat_node, link); seq_printf(m, "\t(%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); } seq_printf(m, "\n"); } seq_printf(m, "\n********** mux_dump help **********\n"); return 0; } #endif static int clk_test_read(struct seq_file *m, void *v) { int i; int cnt; unsigned int value[3]; const char *name; seq_printf(m, "********** clk register dump **********\n"); for (i = 0; i < NR_GRPS; i++) { name = grp_get_name(i); cnt = grp_dump_regs(i, value); if (cnt == 1) { seq_printf(m, "[%02d][%-8s]=[0x%08x]\n", i, name, value[0]); } else if (cnt == 2){ seq_printf(m, "[%02d][%-8s]=[0x%08x][0x%08x]\n", i, name, value[0], value[1]); } else { seq_printf(m, "[%02d][%-8s]=[0x%08x][0x%08x][0x%08x]\n", i, name, value[0], value[1], value[2]); } } seq_printf(m, "\n********** clk_test help **********\n"); seq_printf(m, "enable clk: echo enable id [mod_name] > /proc/clkmgr/clk_test\n"); seq_printf(m, "disable clk: echo disable id [mod_name] > /proc/clkmgr/clk_test\n"); seq_printf(m, "read state: echo id > /proc/clkmgr/clk_test\n"); return 0; } static int clk_test_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { char desc[32]; int len = 0; char cmd[10]; char mod_name[10]; int id; int err; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%s %d %s", cmd, &id, mod_name) == 3) { if (!strcmp(cmd, "enable")) { err = enable_clock(id, mod_name); } else if (!strcmp(cmd, "disable")) { err = disable_clock(id, mod_name); } } else if (sscanf(desc, "%s %d", cmd, &id) == 2) { if (!strcmp(cmd, "enable")) { err = enable_clock(id, "pll_test"); } else if (!strcmp(cmd, "disable")) { err = disable_clock(id, "pll_test"); } } else if (sscanf(desc, "%d", &id) == 1) { clk_info("clock %d is %s\n", id, clock_is_on(id) ? "on" : "off"); } //clk_info("[%s]%s clock %d: result is %d\n", __func__, cmd, id, err); return count; } #ifdef CONFIG_CLKMGR_STAT static int clk_stat_read(struct seq_file *m, void *v) { struct cg_clk *clk; struct list_head *pos; struct stat_node *node; int i, grp, offset; int skip; seq_printf(m, "\n********** clk stat dump **********\n"); for (i = 0; i < NR_CLKS; i++) { grp = i / 32; offset = i % 32; if (offset == 0) { seq_printf(m, "\n*****[%02d][%-8s]*****\n", grp, grp_get_name(grp)); } clk = id_to_clk(i); if (!clk || !clk->grp || !clk->ops->check_validity(clk)) continue; skip = (clk->cnt == 0) && (clk->state == 0) && list_empty(&clk->head); if (skip) continue; seq_printf(m, "[%02d]state=%u, cnt=%u", offset, clk->state, clk->cnt); list_for_each(pos, &clk->head) { node = list_entry(pos, struct stat_node, link); seq_printf(m, "\t(%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); } seq_printf(m, "\n"); } seq_printf(m, "\n********** clk_dump help **********\n"); return 0; } void clk_stat_check(int id) { struct cg_clk *clk; struct list_head *pos; struct stat_node *node; int i, j, grp, offset; int skip; if(id == SYS_DIS) { for(i = CG_DISP0_FROM; i <= CG_DISP0_TO; i++) { grp = i / 32; offset = i % 32; clk = id_to_clk(i); if (!clk || !clk->grp || !clk->ops->check_validity(clk)) continue; skip = (clk->cnt == 0) && (clk->state == 0) && list_empty(&clk->head); if (skip) continue; printk(" [%02d]state=%u, cnt=%u", offset, clk->state, clk->cnt); j = 0; list_for_each(pos, &clk->head) { node = list_entry(pos, struct stat_node, link); printk(" (%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); if(++j % 3 == 0) printk("\n \t\t\t\t "); } printk("\n"); } } } EXPORT_SYMBOL(clk_stat_check); static void clk_stat_bug(void) { struct cg_clk *clk; struct list_head *pos; struct stat_node *node; int i, j, grp, offset; int skip; for (i = 0; i < NR_CLKS; i++) { grp = i / 32; offset = i % 32; if (offset == 0) { printk("\n*****[%02d][%-8s]*****\n", grp, grp_get_name(grp)); } clk = id_to_clk(i); if (!clk || !clk->grp || !clk->ops->check_validity(clk)) continue; skip = (clk->cnt == 0) && (clk->state == 0) && list_empty(&clk->head); if (skip) continue; printk(" [%02d]state=%u, cnt=%u", offset, clk->state, clk->cnt); j = 0; list_for_each(pos, &clk->head) { node = list_entry(pos, struct stat_node, link); printk(" (%s,%u,%u)", node->name, node->cnt_on, node->cnt_off); if(++j % 3 == 0) printk("\n \t\t\t\t "); } printk("\n"); } } #endif void slp_check_pm_mtcmos_pll(void) { int i; clk_info("[%s]\n", __func__); for (i = 2; i < NR_PLLS; i++) { if(i == 7) continue; if (pll_is_on(i)) { clk_info("%s: on\n", plls[i].name); clk_info("suspend warning: %s is on!!!\n", plls[i].name); clk_info("warning! warning! warning! it may cause resume fail\n"); } } for (i = 0; i < NR_SYSS; i++) { if (subsys_is_on(i)) { clk_info("%s: on\n", syss[i].name); if (i > SYS_CONN) { //aee_kernel_warning("Suspend Warning","%s is on", subsyss[i].name); clk_info("suspend warning: %s is on!!!\n", syss[i].name); clk_info("warning! warning! warning! it may cause resume fail\n"); #ifdef CONFIG_CLKMGR_STAT clk_stat_bug(); #endif } } } } EXPORT_SYMBOL(slp_check_pm_mtcmos_pll); static int clk_force_on_read(struct seq_file *m, void *v) { int i; struct cg_clk *clk; seq_printf(m, "********** clk force on info dump **********\n"); for (i = 0; i < NR_CLKS; i++) { clk = &clks[i]; if (clk->force_on) { seq_printf(m, "clock %d (0x%08x @ %s) is force on\n", i, clk->mask, clk->grp->name); } } seq_printf(m, "\n********** clk_force_on help **********\n"); seq_printf(m, "set clk force on: echo set id > /proc/clkmgr/clk_force_on\n"); seq_printf(m, "clr clk force on: echo clr id > /proc/clkmgr/clk_force_on\n"); return 0; } static int clk_force_on_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { char desc[32]; int len = 0; char cmd[10]; int id; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%s %d", cmd, &id) == 2) { if (!strcmp(cmd, "set")) { clk_set_force_on(id); } else if (!strcmp(cmd, "clr")) { clk_clr_force_on(id); } } return count; } //for pll_test static int proc_pll_test_open(struct inode *inode, struct file *file) { return single_open(file, pll_test_read, NULL); } static const struct file_operations pll_test_proc_fops = { .owner = THIS_MODULE, .open = proc_pll_test_open, .read = seq_read, .write = pll_test_write, }; //for pll_fsel static int proc_pll_fsel_open(struct inode *inode, struct file *file) { return single_open(file, pll_fsel_read, NULL); } static const struct file_operations pll_fsel_proc_fops = { .owner = THIS_MODULE, .open = proc_pll_fsel_open, .read = seq_read, .write = pll_fsel_write, }; #ifdef CONFIG_CLKMGR_STAT //for pll_stat static int proc_pll_stat_open(struct inode *inode, struct file *file) { return single_open(file, pll_stat_read, NULL); } static const struct file_operations pll_stat_proc_fops = { .owner = THIS_MODULE, .open = proc_pll_stat_open, .read = seq_read, }; #endif //for subsys_test static int proc_subsys_test_open(struct inode *inode, struct file *file) { return single_open(file, subsys_test_read, NULL); } static const struct file_operations subsys_test_proc_fops = { .owner = THIS_MODULE, .open = proc_subsys_test_open, .read = seq_read, .write = subsys_test_write }; #ifdef CONFIG_CLKMGR_STAT //for subsys_stat static int proc_subsys_stat_open(struct inode *inode, struct file *file) { return single_open(file, subsys_stat_read, NULL); } static const struct file_operations subsys_stat_proc_fops = { .owner = THIS_MODULE, .open = proc_subsys_stat_open, .read = seq_read, }; #endif //for mux_test static int proc_mux_test_open(struct inode *inode, struct file *file) { return single_open(file, mux_test_read, NULL); } static const struct file_operations mux_test_proc_fops = { .owner = THIS_MODULE, .open = proc_mux_test_open, .read = seq_read, }; #ifdef CONFIG_CLKMGR_STAT //for mux_stat static int proc_mux_stat_open(struct inode *inode, struct file *file) { return single_open(file, mux_stat_read, NULL); } static const struct file_operations mux_stat_proc_fops = { .owner = THIS_MODULE, .open = proc_mux_stat_open, .read = seq_read, }; #endif //for clk_test static int proc_clk_test_open(struct inode *inode, struct file *file) { return single_open(file, clk_test_read, NULL); } static const struct file_operations clk_test_proc_fops = { .owner = THIS_MODULE, .open = proc_clk_test_open, .read = seq_read, .write = clk_test_write, }; #ifdef CONFIG_CLKMGR_STAT //for clk_stat static int proc_clk_stat_open(struct inode *inode, struct file *file) { return single_open(file, clk_stat_read, NULL); } static const struct file_operations clk_stat_proc_fops = { .owner = THIS_MODULE, .open = proc_clk_stat_open, .read = seq_read, }; #endif //for clk_force_on static int proc_clk_force_on_open(struct inode *inode, struct file *file) { return single_open(file, clk_force_on_read, NULL); } static const struct file_operations clk_force_on_proc_fops = { .owner = THIS_MODULE, .open = proc_clk_force_on_open, .read = seq_read, .write = clk_force_on_write, }; void mt_clkmgr_debug_init(void) { //use proc_create struct proc_dir_entry *entry; struct proc_dir_entry *clkmgr_dir; clkmgr_dir = proc_mkdir("clkmgr", NULL); if (!clkmgr_dir) { clk_err("[%s]: fail to mkdir /proc/clkmgr\n", __func__); return; } entry = proc_create("pll_test", S_IRUGO | S_IWUSR, clkmgr_dir, &pll_test_proc_fops); entry = proc_create("pll_fsel", S_IRUGO | S_IWUSR, clkmgr_dir, &pll_fsel_proc_fops); #ifdef CONFIG_CLKMGR_STAT entry = proc_create("pll_stat", S_IRUGO, clkmgr_dir, &pll_stat_proc_fops); #endif entry = proc_create("subsys_test", S_IRUGO | S_IWUSR, clkmgr_dir, &subsys_test_proc_fops); #ifdef CONFIG_CLKMGR_STAT entry = proc_create("subsys_stat", S_IRUGO, clkmgr_dir, &subsys_stat_proc_fops); #endif entry = proc_create("mux_test", S_IRUGO, clkmgr_dir, &mux_test_proc_fops); #ifdef CONFIG_CLKMGR_STAT entry = proc_create("mux_stat", S_IRUGO, clkmgr_dir, &mux_stat_proc_fops); #endif entry = proc_create("clk_test", S_IRUGO | S_IWUSR, clkmgr_dir, &clk_test_proc_fops); #ifdef CONFIG_CLKMGR_STAT entry = proc_create("clk_stat", S_IRUGO, clkmgr_dir, &clk_stat_proc_fops); #endif entry = proc_create("clk_force_on", S_IRUGO | S_IWUSR, clkmgr_dir, &clk_force_on_proc_fops); } /*********************************** *for early suspend ************************************/ #ifdef CONFIG_HAS_EARLYSUSPEND static void clkmgr_early_suspend(struct early_suspend *h) { return; } static void clkmgr_late_resume(struct early_suspend *h) { return; } static struct early_suspend mt_clkmgr_early_suspend_handler = { // .level = EARLY_SUSPEND_LEVEL_DISABLE_FB + 250, .level = EARLY_SUSPEND_LEVEL_DISABLE_FB, .suspend = clkmgr_early_suspend, .resume = clkmgr_late_resume, }; #endif //#ifdef CONFIG_HAS_EARLYSUSPEND struct platform_device clkmgr_device = { .name = "CLK", .id = -1, .dev = {}, }; int clk_pm_restore_noirq(struct device *device) { struct subsys *sys; sys = &syss[SYS_DIS]; sys->state = sys->ops->get_state(sys); muxs[MT_MUX_MM].cnt = 1; //plls[VENCPLL].cnt=1; es_flag = 0; clk_set_force_on_locked(&clks[MT_CG_DISP0_SMI_LARB0]); clk_set_force_on_locked(&clks[MT_CG_DISP0_SMI_COMMON]); clk_info("clk_pm_restore_noirq\n"); return 0; } #ifdef CONFIG_PM struct dev_pm_ops clkmgr_pm_ops = { .restore_noirq = clk_pm_restore_noirq, }; #endif #ifdef CONFIG_OF static const struct of_device_id mt_clkmgr_of_match[] = { { .compatible = "mediatek,APMIXED", }, {}, }; #endif static struct platform_driver clkmgr_driver = { .driver = { .name = "CLK", #ifdef CONFIG_PM .pm = &clkmgr_pm_ops, #endif .owner = THIS_MODULE, #ifdef CONFIG_OF .of_match_table = mt_clkmgr_of_match, #endif }, }; #ifdef CONFIG_OF void iomap(void) { struct device_node *node; //apmixed node = of_find_compatible_node(NULL, NULL, "mediatek,APMIXED"); if (!node) { printk("[CLK_APMIXED] find node failed\n"); } clk_apmixed_base = of_iomap(node, 0); if (!clk_apmixed_base) printk("[CLK_APMIXED] base failed\n"); //cksys_base node = of_find_compatible_node(NULL, NULL, "mediatek,TOPCKGEN"); if (!node) { printk("[CLK_CKSYS] find node failed\n"); } clk_cksys_base = of_iomap(node, 0); if (!clk_cksys_base) printk("[CLK_CKSYS] base failed\n"); //infracfg_ao node = of_find_compatible_node(NULL, NULL, "mediatek,INFRACFG_AO"); if (!node) { printk("[CLK_INFRACFG_AO] find node failed\n"); } clk_infracfg_ao_base = of_iomap(node, 0); if (!clk_infracfg_ao_base) printk("[CLK_INFRACFG_AO] base failed\n"); //audio node = of_find_compatible_node(NULL, NULL, "mediatek,AUDIO"); if (!node) { printk("[CLK_AUDIO] find node failed\n"); } clk_audio_base = of_iomap(node, 0); if (!clk_audio_base) printk("[CLK_AUDIO] base failed\n"); //mfgcfg node = of_find_compatible_node(NULL, NULL, "mediatek,G3D_CONFIG"); if (!node) { printk("[CLK_G3D_CONFIG] find node failed\n"); } clk_mfgcfg_base = of_iomap(node, 0); if (!clk_mfgcfg_base) printk("[CLK_G3D_CONFIG] base failed\n"); //mmsys_config node = of_find_compatible_node(NULL, NULL, "mediatek,MMSYS_CONFIG"); if (!node) { printk("[CLK_MMSYS_CONFIG] find node failed\n"); } clk_mmsys_config_base = of_iomap(node, 0); if (!clk_mmsys_config_base) printk("[CLK_MMSYS_CONFIG] base failed\n"); //imgsys node = of_find_compatible_node(NULL, NULL, "mediatek,IMGSYS_CONFIG"); if (!node) { printk("[CLK_IMGSYS_CONFIG] find node failed\n"); } clk_imgsys_base = of_iomap(node, 0); if (!clk_imgsys_base) printk("[CLK_IMGSYS_CONFIG] base failed\n"); //vdec_gcon node = of_find_compatible_node(NULL, NULL, "mediatek,VDEC_GCON"); if (!node) { printk("[CLK_VDEC_GCON] find node failed\n"); } clk_vdec_gcon_base = of_iomap(node, 0); if (!clk_vdec_gcon_base) printk("[CLK_VDEC_GCON] base failed\n"); //mjc_config node = of_find_compatible_node(NULL, NULL, "mediatek,MJC_CONFIG"); if (!node) { printk("[CLK_MJC_CONFIG] find node failed\n"); } clk_mjc_config_base = of_iomap(node, 0); if (!clk_mjc_config_base) printk("[CLK_MJC_CONFIG] base failed\n"); //venc_gcon node = of_find_compatible_node(NULL, NULL, "mediatek,VENC_GCON"); if (!node) { printk("[CLK_VENC_GCON] find node failed\n"); } clk_venc_gcon_base = of_iomap(node, 0); if (!clk_venc_gcon_base) printk("[CLK_VENC_GCON] base failed\n"); } #endif static int mt_clkmgr_debug_module_init(void) { int ret; mt_clkmgr_debug_init(); #ifdef CONFIG_HAS_EARLYSUSPEND register_early_suspend(&mt_clkmgr_early_suspend_handler); #endif ret = platform_device_register(&clkmgr_device); if (ret) { clk_info("clkmgr_device register fail(%d)\n", ret); return ret; } ret = platform_driver_register(&clkmgr_driver); if (ret) { clk_info("clkmgr_driver register fail(%d)\n", ret); return ret; } return 0; } static int __init mt_clkmgr_late_init(void) { mt_enable_clock(MT_CG_INFRA_SPI, "clkmgr"); mt_disable_clock(MT_CG_INFRA_SPI, "clkmgr"); mt_enable_clock(MT_CG_INFRA_MSDC_2, "clkmgr"); mt_disable_clock(MT_CG_INFRA_MSDC_2, "clkmgr"); mt_enable_clock(MT_CG_INFRA_MSDC_3, "clkmgr"); mt_disable_clock(MT_CG_INFRA_MSDC_3, "clkmgr"); mt_enable_clock(MT_CG_DISP1_DPI_PIXEL, "clkmgr"); mt_disable_clock(MT_CG_DISP1_DPI_PIXEL, "clkmgr"); enable_mux(MT_MUX_AUD1, "clkmgr"); disable_mux(MT_MUX_AUD1, "clkmgr"); enable_mux(MT_MUX_AUD2, "clkmgr"); disable_mux(MT_MUX_AUD2, "clkmgr"); enable_pll(VENCPLL, "clkmgr"); disable_pll(VENCPLL, "clkmgr"); return 0; } module_init(mt_clkmgr_debug_module_init); late_initcall(mt_clkmgr_late_init); /*************CLKM****************/ #if 0 int clk_monitor_0(enum ckmon_sel ckmon, enum monitor_clk_sel_0 sel, int div) { unsigned long flags; unsigned int temp; if((div > 255) || (ckmon>0)) { clk_info("CLK_Monitor_0 error parameter\n"); return 1; } clkmgr_lock(flags); temp = clk_readl(CLK26CALI_0); clk_writel(CLK26CALI_0, temp|0x80); clk_writel(CLK_CFG_8, sel<<8); temp = clk_readl(CLK_MISC_CFG_1); clk_writel(CLK_MISC_CFG_1, div&0xff); clk_info("CLK_Monitor_0 Reg: CLK26CALI_0=0x%x, CLK_CFG_8=0x%x, CLK_MISC_CFG_1=0x%x\n", clk_readl(CLK26CALI_0), clk_readl(CLK_CFG_8), clk_readl(CLK_MISC_CFG_1)); clkmgr_unlock(flags); return 0; } EXPORT_SYMBOL(clk_monitor_0); int clk_monitor(enum ckmon_sel ckmon, enum monitor_clk_sel sel, int div) { unsigned long flags; unsigned int ckmon_shift=0; unsigned int temp; if((div > 255) || (ckmon==0)) { clk_info("CLK_Monitor error parameter\n"); return 1; } clkmgr_lock(flags); if(ckmon==1) ckmon_shift=0; else if(ckmon==2) ckmon_shift=8; else if(ckmon==3) ckmon_shift=16; temp = clk_readl(CLK_CFG_10); temp = temp & (~(0xf<<ckmon_shift)); temp = temp | ((sel&0xf)<<ckmon_shift); clk_writel(CLK_CFG_10, temp); temp = clk_readl(CLK_CFG_11); temp = temp & (~(0xff<<ckmon_shift)); temp = temp | ((div&0xff)<<ckmon_shift); clk_writel(CLK_CFG_11, temp); clk_info("CLK_Monitor Reg: CLK_CFG_10=0x%x, CLK_CFG_11=0x%x\n", clk_readl(CLK_CFG_10), clk_readl(CLK_CFG_11)); clkmgr_unlock(flags); return 0; } EXPORT_SYMBOL(clk_monitor); #endif
gpl-2.0
tobiasbuhrer/tobiasb
web/core/modules/language/tests/src/Kernel/LanguageConfigFactoryOverrideTest.php
1290
<?php namespace Drupal\Tests\language\Kernel; use Drupal\language\Entity\ConfigurableLanguage; use Drupal\KernelTests\KernelTestBase; /** * Tests \Drupal\language\Config\LanguageConfigFactoryOverride. * * @group language */ class LanguageConfigFactoryOverrideTest extends KernelTestBase { /** * Modules to enable. * * @var array */ protected static $modules = ['system', 'language']; /** * Tests language.config_factory_override service has the default language. */ public function testLanguageConfigFactoryOverride() { $this->installConfig('system'); $this->installConfig('language'); /** @var \Drupal\language\Config\LanguageConfigFactoryOverride $config_factory_override */ $config_factory_override = \Drupal::service('language.config_factory_override'); $this->assertEquals('en', $config_factory_override->getLanguage()->getId()); ConfigurableLanguage::createFromLangcode('de')->save(); // Invalidate the container. $this->config('system.site')->set('default_langcode', 'de')->save(); $this->container->get('kernel')->rebuildContainer(); $config_factory_override = \Drupal::service('language.config_factory_override'); $this->assertEquals('de', $config_factory_override->getLanguage()->getId()); } }
gpl-2.0
godvmxi/os_30_cn
project/day_23/int.c
1420
/* ================================================================== ×¢ÊÍ£ºÕ¬ ʱ¼ä£º2013Äê2ÔÂ22ÈÕ ¸ÃÎļþÖж¨ÒåÁËÓëÖжÏÓйصĺ¯Êý ================================================================== */ #include "bootpack.h" #include <stdio.h> /* ¹ØÓÚ8259AµÄÏà¹ØÄÚÈݿɲο¼ÕÔ²©Ê¿µÄ¡¶Linux ÄÚºËÍêÈ«ÆÊÎö¡ª¡ª»ùÓÚ0.11Äںˡ·P215 ÊéÖжÔ8259AÓÐÏêϸµÄ½éÉÜ */ /* ³õʼ»¯PIC */ void init_pic(void) { io_out8(PIC0_IMR, 0xff ); /* ½ûÖ¹Ö÷PICËùÓÐÖÐ¶Ï */ io_out8(PIC1_IMR, 0xff ); /* ½ûÖ¹´ÓPICËùÓÐÖÐ¶Ï */ io_out8(PIC0_ICW1, 0x11 ); /* ÐèÒªICW4£¬ ¶àƬ¼¶Áª£¬ ±ßÑØ´¥·¢·½Ê½ */ io_out8(PIC0_ICW2, 0x20 ); /* IRQ0-7ÓÉÓÚINT 0x20~0x27½ÓÊÕ */ io_out8(PIC0_ICW3, 1 << 2); /* PIC1ÓÉIRQ2Á¬½Ó */ io_out8(PIC0_ICW4, 0x01 ); /* ÆÕͨȫǶÌ× ·Ç»º³å ·Ç×Ô¶¯½áÊøÖжϷ½Ê½ */ io_out8(PIC1_ICW1, 0x11 ); /* ÐèÒªICW4£¬ ¶àƬ¼¶Áª£¬ ±ßÑØ´¥·¢·½Ê½ */ io_out8(PIC1_ICW2, 0x28 ); /* IRQ8-15ÓÉÓÚINT 0x28~0x2f½ÓÊÕ */ io_out8(PIC1_ICW3, 2 ); /* PIC1ÓÉIRQ2Á¬½Ó */ io_out8(PIC1_ICW4, 0x01 ); /* ÆÕͨȫǶÌ× ·Ç»º³å ·Ç×Ô¶¯½áÊøÖжϷ½Ê½ */ io_out8(PIC0_IMR, 0xfb ); /* 11111011 PIC1ÒÔÍâÈ«²¿½ûÖ¹ */ io_out8(PIC1_IMR, 0xff ); /* 11111111 ½ûÖ¹´ÓPICËùÓÐÖÐ¶Ï */ return; } /* ´¦ÀíIRQ7ÖÐ¶Ï ÓÉnaskfunc.nasÖеÄ_asm_inthandler27µ÷Óà */ /* ¹ØÓÚIRQ7µÄ´¦Àí¿É¶ÔÕÕÕÔ²©Ê¿µÄ¡¶Linux ÄÚºËÍêÈ«ÆÊÎö¡ª¡ª»ùÓÚ0.11Äںˡ·P219 µÄ±í¸ñÀ´Àí½â */ void inthandler27(int *esp) { io_out8(PIC0_OCW2, 0x67); /* Ö±½Ó·¢ËÍEOIÃüÁî ±íʾÖжϴ¦Àí½áÊø */ return; }
gpl-2.0
golismero/golismero
tools/sqlmap/plugins/generic/search.py
26113
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.agent import agent from lib.core.common import arrayizeValue from lib.core.common import Backend from lib.core.common import filterPairValues from lib.core.common import getLimitRange from lib.core.common import isInferenceAvailable from lib.core.common import isNoneValue from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core.common import readInput from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import safeStringFormat from lib.core.common import unArrayizeValue from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.exception import SqlmapUserQuitException from lib.core.settings import CURRENT_DB from lib.core.settings import METADB_SUFFIX from lib.request import inject from lib.techniques.brute.use import columnExists from lib.techniques.brute.use import tableExists class Search: """ This class defines search functionalities for plugins. """ def __init__(self): pass def searchDb(self): foundDbs = [] rootQuery = queries[Backend.getIdentifiedDbms()].search_db dbList = conf.db.split(",") if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: dbCond = rootQuery.inband.condition2 else: dbCond = rootQuery.inband.condition dbConsider, dbCondParam = self.likeOrExact("database") for db in dbList: values = [] db = safeSQLIdentificatorNaming(db) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): db = db.upper() infoMsg = "searching database" if dbConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) if conf.excludeSysDbs: exclDbsQuery = "".join(" AND '%s' != %s" % (unsafeSQLIdentificatorNaming(db), dbCond) for db in self.excludeDbsList) infoMsg = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList)) logger.info(infoMsg) else: exclDbsQuery = "" dbQuery = "%s%s" % (dbCond, dbCondParam) dbQuery = dbQuery % unsafeSQLIdentificatorNaming(db) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.inband.query2 else: query = rootQuery.inband.query query = query % (dbQuery + exclDbsQuery) values = inject.getValue(query, blind=False, time=False) if not isNoneValue(values): values = arrayizeValue(values) for value in values: value = safeSQLIdentificatorNaming(value) foundDbs.append(value) if not values and isInferenceAvailable() and not conf.direct: infoMsg = "fetching number of database" if dbConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(db) logger.info(infoMsg) if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.count2 else: query = rootQuery.blind.count query = query % (dbQuery + exclDbsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no database" if dbConsider == "1": warnMsg += "s like" warnMsg += " '%s' found" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: query = rootQuery.blind.query2 else: query = rootQuery.blind.query query = query % (dbQuery + exclDbsQuery) query = agent.limitQuery(index, query, dbCond) value = unArrayizeValue(inject.getValue(query, union=False, error=False)) value = safeSQLIdentificatorNaming(value) foundDbs.append(value) conf.dumper.lister("found databases", foundDbs) def searchTable(self): bruteForce = False if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" bruteForce = True if bruteForce: message = "do you want to use common table existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: regex = "|".join(conf.tbl.split(",")) return tableExists(paths.COMMON_TABLES, regex) foundTbls = {} tblList = conf.tbl.split(",") rootQuery = queries[Backend.getIdentifiedDbms()].search_table tblCond = rootQuery.inband.condition dbCond = rootQuery.inband.condition2 tblConsider, tblCondParam = self.likeOrExact("table") for tbl in tblList: values = [] tbl = safeSQLIdentificatorNaming(tbl, True) if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.FIREBIRD): tbl = tbl.upper() infoMsg = "searching table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) if dbCond and conf.db and conf.db != CURRENT_DB: _ = conf.db.split(",") whereDbsQuery = " AND (" + " OR ".join("%s = '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in _) + ")" infoMsg += " for database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(db for db in _)) elif conf.excludeSysDbs: whereDbsQuery = "".join(" AND '%s' != %s" % (unsafeSQLIdentificatorNaming(db), dbCond) for db in self.excludeDbsList) infoMsg2 = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(db for db in self.excludeDbsList)) logger.info(infoMsg2) else: whereDbsQuery = "" logger.info(infoMsg) tblQuery = "%s%s" % (tblCond, tblCondParam) tblQuery = tblQuery % unsafeSQLIdentificatorNaming(tbl) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: query = rootQuery.inband.query query = query % (tblQuery + whereDbsQuery) values = inject.getValue(query, blind=False, time=False) if values and Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.FIREBIRD): newValues = [] if isinstance(values, basestring): values = [values] for value in values: dbName = "SQLite" if Backend.isDbms(DBMS.SQLITE) else "Firebird" newValues.append(["%s%s" % (dbName, METADB_SUFFIX), value]) values = newValues for foundDb, foundTbl in filterPairValues(values): foundDb = safeSQLIdentificatorNaming(foundDb) foundTbl = safeSQLIdentificatorNaming(foundTbl, True) if foundDb is None or foundTbl is None: continue if foundDb in foundTbls: foundTbls[foundDb].append(foundTbl) else: foundTbls[foundDb] = [foundTbl] if not values and isInferenceAvailable() and not conf.direct: if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): if len(whereDbsQuery) == 0: infoMsg = "fetching number of databases with table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) logger.info(infoMsg) query = rootQuery.blind.count query = query % (tblQuery + whereDbsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no databases have table" if tblConsider == "1": warnMsg += "s like" warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(tbl) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query % (tblQuery + whereDbsQuery) query = agent.limitQuery(index, query) foundDb = unArrayizeValue(inject.getValue(query, union=False, error=False)) foundDb = safeSQLIdentificatorNaming(foundDb) if foundDb not in foundTbls: foundTbls[foundDb] = [] if tblConsider == "2": foundTbls[foundDb].append(tbl) if tblConsider == "2": continue else: for db in conf.db.split(","): db = safeSQLIdentificatorNaming(db) if db not in foundTbls: foundTbls[db] = [] else: dbName = "SQLite" if Backend.isDbms(DBMS.SQLITE) else "Firebird" foundTbls["%s%s" % (dbName, METADB_SUFFIX)] = [] for db in foundTbls.keys(): db = safeSQLIdentificatorNaming(db) infoMsg = "fetching number of table" if tblConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (unsafeSQLIdentificatorNaming(tbl), unsafeSQLIdentificatorNaming(db)) logger.info(infoMsg) query = rootQuery.blind.count2 if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): query = query % unsafeSQLIdentificatorNaming(db) query += " AND %s" % tblQuery count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no table" if tblConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % unsafeSQLIdentificatorNaming(tbl) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query2 if query.endswith("'%s')"): query = query[:-1] + " AND %s)" % tblQuery else: query += " AND %s" % tblQuery if Backend.isDbms(DBMS.FIREBIRD): query = safeStringFormat(query, index) if Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.FIREBIRD): query = safeStringFormat(query, unsafeSQLIdentificatorNaming(db)) if not Backend.isDbms(DBMS.FIREBIRD): query = agent.limitQuery(index, query) foundTbl = unArrayizeValue(inject.getValue(query, union=False, error=False)) if not isNoneValue(foundTbl): kb.hintValue = foundTbl foundTbl = safeSQLIdentificatorNaming(foundTbl, True) foundTbls[db].append(foundTbl) for db in foundTbls.keys(): if isNoneValue(foundTbls[db]): del foundTbls[db] if not foundTbls: warnMsg = "no databases contain any of the provided tables" logger.warn(warnMsg) return conf.dumper.dbTables(foundTbls) self.dumpFoundTables(foundTbls) def searchColumn(self): bruteForce = False if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" bruteForce = True if bruteForce: message = "do you want to use common column existence check? %s" % ("[Y/n/q]" if Backend.getIdentifiedDbms() in (DBMS.ACCESS,) else "[y/N/q]") test = readInput(message, default="Y" if "Y" in message else "N") if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): raise SqlmapUserQuitException else: regex = "|".join(conf.col.split(",")) conf.dumper.dbTableColumns(columnExists(paths.COMMON_COLUMNS, regex)) message = "do you want to dump entries? [Y/n] " output = readInput(message, default="Y") if output and output[0] not in ("n", "N"): self.dumpAll() return rootQuery = queries[Backend.getIdentifiedDbms()].search_column foundCols = {} dbs = {} whereDbsQuery = "" whereTblsQuery = "" infoMsgTbl = "" infoMsgDb = "" colList = conf.col.split(",") origTbl = conf.tbl origDb = conf.db colCond = rootQuery.inband.condition dbCond = rootQuery.inband.condition2 tblCond = rootQuery.inband.condition3 colConsider, colCondParam = self.likeOrExact("column") for column in colList: values = [] column = safeSQLIdentificatorNaming(column) conf.db = origDb conf.tbl = origTbl if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): column = column.upper() infoMsg = "searching column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) foundCols[column] = {} if conf.tbl: _ = conf.tbl.split(",") whereTblsQuery = " AND (" + " OR ".join("%s = '%s'" % (tblCond, unsafeSQLIdentificatorNaming(tbl)) for tbl in _) + ")" infoMsgTbl = " for table%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(tbl) for tbl in _)) if conf.db and conf.db != CURRENT_DB: _ = conf.db.split(",") whereDbsQuery = " AND (" + " OR ".join("%s = '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in _) + ")" infoMsgDb = " in database%s '%s'" % ("s" if len(_) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(db) for db in _)) elif conf.excludeSysDbs: whereDbsQuery = "".join(" AND %s != '%s'" % (dbCond, unsafeSQLIdentificatorNaming(db)) for db in self.excludeDbsList) infoMsg2 = "skipping system database%s '%s'" % ("s" if len(self.excludeDbsList) > 1 else "", ", ".join(unsafeSQLIdentificatorNaming(db) for db in self.excludeDbsList)) logger.info(infoMsg2) else: infoMsgDb = " across all databases" logger.info("%s%s%s" % (infoMsg, infoMsgTbl, infoMsgDb)) colQuery = "%s%s" % (colCond, colCondParam) colQuery = colQuery % unsafeSQLIdentificatorNaming(column) if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: if not all((conf.db, conf.tbl)): # Enumerate tables containing the column provided if # either of database(s) or table(s) is not provided query = rootQuery.inband.query query = query % (colQuery + whereDbsQuery + whereTblsQuery) values = inject.getValue(query, blind=False, time=False) else: # Assume provided databases' tables contain the # column(s) provided values = [] for db in conf.db.split(","): for tbl in conf.tbl.split(","): values.append([safeSQLIdentificatorNaming(db), safeSQLIdentificatorNaming(tbl, True)]) for db, tbl in filterPairValues(values): db = safeSQLIdentificatorNaming(db) tbls = tbl.split(",") if not isNoneValue(tbl) else [] for tbl in tbls: tbl = safeSQLIdentificatorNaming(tbl, True) if db is None or tbl is None: continue conf.db = db conf.tbl = tbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and tbl in kb.data.cachedColumns[db]: if db not in dbs: dbs[db] = {} if tbl not in dbs[db]: dbs[db][tbl] = {} dbs[db][tbl].update(kb.data.cachedColumns[db][tbl]) if db in foundCols[column]: foundCols[column][db].append(tbl) else: foundCols[column][db] = [tbl] kb.data.cachedColumns = {} if not values and isInferenceAvailable() and not conf.direct: if not conf.db: infoMsg = "fetching number of databases with tables containing column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) logger.info("%s%s%s" % (infoMsg, infoMsgTbl, infoMsgDb)) query = rootQuery.blind.count query = query % (colQuery + whereDbsQuery + whereTblsQuery) count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no databases have tables containing column" if colConsider == "1": warnMsg += "s like" warnMsg += " '%s'" % unsafeSQLIdentificatorNaming(column) logger.warn("%s%s" % (warnMsg, infoMsgTbl)) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query query = query % (colQuery + whereDbsQuery + whereTblsQuery) query = agent.limitQuery(index, query) db = unArrayizeValue(inject.getValue(query, union=False, error=False)) db = safeSQLIdentificatorNaming(db) if db not in dbs: dbs[db] = {} if db not in foundCols[column]: foundCols[column][db] = [] else: for db in conf.db.split(","): db = safeSQLIdentificatorNaming(db) if db not in foundCols[column]: foundCols[column][db] = [] origDb = conf.db origTbl = conf.tbl for column, dbData in foundCols.items(): colQuery = "%s%s" % (colCond, colCondParam) colQuery = colQuery % unsafeSQLIdentificatorNaming(column) for db in dbData: conf.db = origDb conf.tbl = origTbl infoMsg = "fetching number of tables containing column" if colConsider == "1": infoMsg += "s like" infoMsg += " '%s' in database '%s'" % (unsafeSQLIdentificatorNaming(column), unsafeSQLIdentificatorNaming(db)) logger.info(infoMsg) query = rootQuery.blind.count2 query = query % unsafeSQLIdentificatorNaming(db) query += " AND %s" % colQuery query += whereTblsQuery count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS) if not isNumPosStrValue(count): warnMsg = "no tables contain column" if colConsider == "1": warnMsg += "s like" warnMsg += " '%s' " % unsafeSQLIdentificatorNaming(column) warnMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(db) logger.warn(warnMsg) continue indexRange = getLimitRange(count) for index in indexRange: query = rootQuery.blind.query2 if query.endswith("'%s')"): query = query[:-1] + " AND %s)" % (colQuery + whereTblsQuery) else: query += " AND %s" % (colQuery + whereTblsQuery) query = safeStringFormat(query, unsafeSQLIdentificatorNaming(db)) query = agent.limitQuery(index, query) tbl = unArrayizeValue(inject.getValue(query, union=False, error=False)) kb.hintValue = tbl tbl = safeSQLIdentificatorNaming(tbl, True) conf.db = db conf.tbl = tbl conf.col = column self.getColumns(onlyColNames=True, colTuple=(colConsider, colCondParam), bruteForce=False) if db in kb.data.cachedColumns and tbl in kb.data.cachedColumns[db]: if db not in dbs: dbs[db] = {} if tbl not in dbs[db]: dbs[db][tbl] = {} dbs[db][tbl].update(kb.data.cachedColumns[db][tbl]) kb.data.cachedColumns = {} if db in foundCols[column]: foundCols[column][db].append(tbl) else: foundCols[column][db] = [tbl] if dbs: conf.dumper.dbColumns(foundCols, colConsider, dbs) self.dumpFoundColumn(dbs, foundCols, colConsider) else: warnMsg = "no databases have tables containing any of the " warnMsg += "provided columns" logger.warn(warnMsg) def search(self): if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): for item in ('db', 'tbl', 'col'): if getattr(conf, item, None): setattr(conf, item, getattr(conf, item).upper()) if conf.col: self.searchColumn() elif conf.tbl: self.searchTable() elif conf.db: self.searchDb() else: errMsg = "missing parameter, provide -D, -T or -C along " errMsg += "with --search" raise SqlmapMissingMandatoryOptionException(errMsg)
gpl-2.0
yeKcim/warmux
trunk/build/symbian/lib/stlport/src/num_put_float.cpp
34762
/* * Copyright (c) 1999 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ #include "stlport_prefix.h" #include <cmath> #include <ios> #include <locale> #if defined (__DECCXX) # define NDIG 400 #else # define NDIG 82 #endif #if defined (_STLP_NO_LONG_DOUBLE) # define MAXECVT 17 # define MAXFCVT 18 typedef double max_double_type; #else # define MAXECVT 35 # define MAXFCVT 36 typedef long double max_double_type; #endif #define MAXFSIG MAXECVT #define MAXESIZ 5 #define todigit(x) ((x)+'0') #if defined (_STLP_UNIX) # if defined (__sun) # include <floatingpoint.h> # endif # if defined (__sun) || defined (__digital__) || defined (__sgi) || defined (_STLP_SCO_OPENSERVER) || defined (__NCR_SVR) // DEC, SGI & Solaris need this # include <values.h> # include <nan.h> # endif # if defined (__QNXNTO__) || ( defined(__GNUC__) && defined(__APPLE__) ) || defined(_STLP_USE_UCLIBC) /* 0.9.26 */ || \ defined(__FreeBSD__) # define USE_SPRINTF_INSTEAD # endif # if defined( _AIX ) // JFA 3-Aug-2000 # include <math.h> # include <float.h> # endif #endif #include <cstdio> #include <cstdlib> //#if defined(_CRAY) //# include <stdlib.h> //#endif #if defined (_STLP_MSVC_LIB) || defined (__MINGW32__) || defined (__BORLANDC__) || defined (__DJGPP) || \ defined (_STLP_SCO_OPENSERVER) || defined (__NCR_SVR) # include <float.h> #endif #if defined(__MRC__) || defined(__SC__) || defined(_CRAY) //*TY 02/24/2000 - added support for MPW # include <fp.h> #endif #if defined (__CYGWIN__) # include <ieeefp.h> #endif #if defined (__MSL__) # include <cstdlib> // for atoi # include <cstdio> // for snprintf # include <algorithm> # include <cassert> #endif #if defined (__ISCPP__) # include <cfloat> #endif #include <algorithm> #if defined (__DMC__) # define snprintf _snprintf #endif #if defined (__SYMBIAN32__) # include <e32math.h> static char* _symbian_ecvt(double x, int n, int* pt, int* sign, char* buf) { // normalize sign and set sign bit if (x < 0) { if (sign) *sign = 1; x = -x; } else if (sign) *sign = 0; // initialize end-of-buffer char* end = buf+n; *end = 0; // if buffer will be empty anyway, return now if (n == 0) return buf; // normalize number and set point position if (x != 0.0) { double fex; if (Math::Log(fex, x) != KErrNone) return buf; int ex = (int)fex; if (x < 1.0) --ex; if (ex != 0) { double temp; if (Math::Pow10(temp, ex) != KErrNone) return buf; x /= temp; } if (pt) *pt = ex + 1; } else if (pt) *pt = 1; const double dbl_epsilon = 2.2204460492503131e-16; // render digits (except for last digit) char* ptr = buf; for (; (ptr+1)!=end; ++ptr) { char digit = (char)x; *ptr = '0' + digit; x = (x - (double)digit) * 10.0 * (1.0 + dbl_epsilon); } // render last digit, rounded double rx; if (Math::Round(rx, x, 0) != KErrNone) return buf; *ptr = '0' + (char)rx; // detect carry on last digit and propagate it back for (; ptr!=buf && *ptr==':'; --ptr) { *ptr = '0'; ++*(ptr-1); } // detect overflow on first digit and, in case, shift // the sequence forward if (*buf == ':') { *buf = '0'; memcpy(buf+1, buf, n-1); *buf = '1'; if (pt) ++*pt; } return buf; } static char* _symbian_fcvt(double x, int n, int* pt, int* sign, char* buf) { *buf = 0; if (x < 0.0) { *sign = 1; x = -x; } else *sign = 0; double fx; if (Math::Int(fx, x) != KErrNone) return buf; if (fx != 0.0 || x == 0.0 || n == 0) { int fn = 1; if (fx != 0.0) { double temp; if (Math::Log(temp, fx) != KErrNone) return buf; fn += (int)temp; } _symbian_ecvt(fx, fn, pt, 0, buf); } else *pt = 0; if (n != 0) { const double dx = x - fx; _symbian_ecvt(dx, n, 0, 0, buf+*pt); } return buf; } #endif #if defined(__hpux) && (!defined(_INCLUDE_HPUX_SOURCE) || defined(__GNUC__)) extern "C" double erf(double); extern "C" double erfc(double); extern "C" double gamma(double); /* obsolescent */ extern "C" double hypot(double, double); extern "C" int isnan(double); extern "C" double j0(double); extern "C" double j1(double); extern "C" double jn(int, double); extern "C" double lgamma(double); extern "C" double y0(double); extern "C" double y1(double); extern "C" double yn(int, double); # define HUGE_VALF _SINFINITY # define INFINITY _SINFINITY # define NAN _SQNAN # define isnan(x) _ISNAN(x) # define isinf(x) _ISINF(x) # define signbit(x) _SIGNBIT(x) # define isfinite(x) _ISFINITE(x) # define isnormal(x) _ISNORMAL(x) # define fpclassify(x) _FPCLASSIFY(x) # define isunordered(x,y) _ISUNORDERED(x,y) # define isgreater(x,y) _ISGREATER(x,y) # define isgreaterequal(x,y) _ISGREATEREQUAL(x,y) # define isless(x,y) _ISLESS(x,y) # define islessequal(x,y) _ISLESSEQUAL(x,y) # define islessgreater(x,y) _ISLESSGREATER(x,y) # define FP_NORMAL 0 # define FP_ZERO 1 # define FP_INFINITE 2 # define FP_SUBNORMAL 3 # define FP_NAN 4 # define DECIMAL_DIG 17 # define _IS64(x) (sizeof(x) == sizeof(double)) # define _IS32(x) (sizeof(x) == sizeof(float)) extern "C" { extern double copysign(double, double); extern const float _SINFINITY; extern const float _SQNAN; //# if defined (_PA_RISC) # define _ISNAN(x) (_IS32(x)?_Isnanf(x):(isnan)(x)) # define _ISINF(x) (_IS32(x)?_Isinff(x):_Isinf(x)) # define _SIGNBIT(x) (_IS32(x)?_Signbitf(x):_Signbit(x)) # define _ISFINITE(x) (_IS32(x)?_Isfinitef(x):_Isfinite(x)) # define _ISNORMAL(x) (_IS32(x)?_Isnormalf(x):_Isnormal(x)) # define _FPCLASSIFY(x) (_IS32(x)?_Fpclassifyf(x)>>1:_Fpclassify(x)>>1) # define _ISUNORDERED(x,y) (_IS32(x)&&_IS32(y)?_Isunorderedf(x,y):_Isunordered(x,y)) extern int _Signbit(double); extern int _Signbitf(float); extern int _Isnanf(float); extern int _Isfinite(double); extern int _Isfinitef(float); extern int _Isinf(double); extern int _Isinff(float); extern int _Isnormal(double); extern int _Isnormalf(float); extern int _Isunordered(double, double); extern int _Isunorderedf(float, float); extern int _Fpclassify(double); extern int _Fpclassifyf(float); //# else //# include "math_ia64_internal.h" //# define _FPCLASSIFY(x) (_IS32(x)?_Fpclassf(x):_Fpclass(x)) // extern int _Fpclass(double); // extern int _Fpclassf(float); //# endif } # if !defined (_INCLUDE_XOPEN_SOURCE_EXTENDED) extern "C" char *fcvt(double, int, int *, int *); extern "C" char *ecvt(double, int, int *, int *); # endif # if !defined (_INCLUDE_HPUX_SOURCE) # if !defined (_LONG_DOUBLE) # define _LONG_DOUBLE typedef struct { uint32_t word1, word2, word3, word4; } long_double; # endif /* _LONG_DOUBLE */ extern "C" char *_ldecvt(long_double, int, int *, int *); extern "C" char *_ldfcvt(long_double, int, int *, int *); # endif #endif /* __hpux */ _STLP_BEGIN_NAMESPACE _STLP_MOVE_TO_PRIV_NAMESPACE #if defined (__MWERKS__) || defined(__BEOS__) # define USE_SPRINTF_INSTEAD #endif #if defined (_AIX) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) // Some OS'es only provide non-reentrant primitives, so we have to use additional synchronization here # if !defined(_REENTRANT) && !defined(_THREAD_SAFE) && !(defined(_POSIX_THREADS) && defined(__OpenBSD__)) # define LOCK_CVT # define RETURN_CVT(ecvt, x, n, pt, sign, buf) return ecvt(x, n, pt, sign); # else static _STLP_STATIC_MUTEX __put_float_mutex _STLP_MUTEX_INITIALIZER; # define LOCK_CVT _STLP_auto_lock lock(__put_float_mutex); # define RETURN_CVT(ecvt, x, n, pt, sign, buf) strcpy(buf, ecvt(x, n, pt, sign)); return buf; # endif // !_REENTRANT #endif // _AIX || __FreeBSD__ || __NetBSD__ || __OpenBSD__ // Tests for infinity and NaN differ on different OSs. We encapsulate // these differences here. #if !defined (USE_SPRINTF_INSTEAD) # if defined (__hpux) || defined (__DJGPP) || (defined (_STLP_USE_GLIBC) && ! defined (__MSL__)) || \ defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) static inline bool _Stl_is_nan_or_inf(double x) # if defined (isfinite) { return !isfinite(x); } # else { return !finite(x); } # endif static inline bool _Stl_is_neg_nan(double x) { return isnan(x) && ( copysign(1., x) < 0 ); } static inline bool _Stl_is_inf(double x) { return isinf(x); } // inline bool _Stl_is_neg_inf(double x) { return isinf(x) < 0; } static inline bool _Stl_is_neg_inf(double x) { return isinf(x) && x < 0; } # elif (defined (__unix) || defined (__unix__)) && \ !defined (__APPLE__) && !defined (__DJGPP) && !defined(__osf__) && \ !defined (_CRAY) static inline bool _Stl_is_nan_or_inf(double x) { return IsNANorINF(x); } static inline bool _Stl_is_inf(double x) { return IsNANorINF(x) && IsINF(x); } static inline bool _Stl_is_neg_inf(double x) { return (IsINF(x)) && (x < 0.0); } static inline bool _Stl_is_neg_nan(double x) { return IsNegNAN(x); } # elif defined (__BORLANDC__) && ( __BORLANDC__ < 0x540 ) static inline bool _Stl_is_nan_or_inf(double x) { return !_finite(x); } static inline bool _Stl_is_inf(double x) { return _Stl_is_nan_or_inf(x) && ! _isnan(x);} static inline bool _Stl_is_neg_inf(double x) { return _Stl_is_inf(x) && x < 0 ; } static inline bool _Stl_is_neg_nan(double x) { return _isnan(x) && x < 0 ; } # elif defined (_STLP_MSVC_LIB) || defined (__MINGW32__) || defined (__BORLANDC__) static inline bool _Stl_is_nan_or_inf(double x) { return !_finite(x); } static inline bool _Stl_is_inf(double x) { int fclass = _fpclass(x); return fclass == _FPCLASS_NINF || fclass == _FPCLASS_PINF; } static inline bool _Stl_is_neg_inf(double x) { return _fpclass(x) == _FPCLASS_NINF; } static inline bool _Stl_is_neg_nan(double x) { return _isnan(x) && _copysign(1., x) < 0 ; } # elif defined (__MRC__) || defined (__SC__) //*TY 02/24/2000 - added support for MPW static bool _Stl_is_nan_or_inf(double x) { return isnan(x) || !isfinite(x); } static bool _Stl_is_inf(double x) { return !isfinite(x); } static bool _Stl_is_neg_inf(double x) { return !isfinite(x) && signbit(x); } static bool _Stl_is_neg_nan(double x) { return isnan(x) && signbit(x); } # elif /* defined(__FreeBSD__) || defined(__OpenBSD__) || */ (defined(__GNUC__) && defined(__APPLE__)) static inline bool _Stl_is_nan_or_inf(double x) { return !finite(x); } static inline bool _Stl_is_inf(double x) { return _Stl_is_nan_or_inf(x) && ! isnan(x); } static inline bool _Stl_is_neg_inf(double x) { return _Stl_is_inf(x) && x < 0 ; } static inline bool _Stl_is_neg_nan(double x) { return isnan(x) && copysign(1., x) < 0 ; } # elif defined( _AIX ) // JFA 11-Aug-2000 static bool _Stl_is_nan_or_inf(double x) { return isnan(x) || !finite(x); } static bool _Stl_is_inf(double x) { return !finite(x); } // bool _Stl_is_neg_inf(double x) { return _class(x) == FP_MINUS_INF; } static bool _Stl_is_neg_inf(double x) { return _Stl_is_inf(x) && ( copysign(1., x) < 0 ); } static bool _Stl_is_neg_nan(double x) { return isnan(x) && ( copysign(1., x) < 0 ); } # elif defined (__ISCPP__) static inline bool _Stl_is_nan_or_inf (double x) { return _fp_isINF(x) || _fp_isNAN(x); } static inline bool _Stl_is_inf (double x) { return _fp_isINF(x); } static inline bool _Stl_is_neg_inf (double x) { return _fp_isINF(x) && x < 0; } static inline bool _Stl_is_neg_nan (double x) { return _fp_isNAN(x) && x < 0; } # elif defined (_CRAY) # if defined (_CRAYIEEE) static inline bool _Stl_is_nan_or_inf(double x) { return isnan(x) || isinf(x); } static inline bool _Stl_is_inf(double x) { return isinf(x); } static inline bool _Stl_is_neg_inf(double x) { return isinf(x) && signbit(x); } static inline bool _Stl_is_neg_nan(double x) { return isnan(x) && signbit(x); } # else static inline bool _Stl_is_nan_or_inf(double x) { return false; } static inline bool _Stl_is_inf(double x) { return false; } static inline bool _Stl_is_neg_inf(double x) { return false; } static inline bool _Stl_is_neg_nan(double x) { return false; } # endif # elif defined (__SYMBIAN32__) static inline bool _Stl_is_nan_or_inf(double x) { return Math::IsNaN(x) || Math::IsInfinite(x); } static inline bool _Stl_is_inf(double x) { return Math::IsInfinite(x); } static inline bool _Stl_is_neg_inf(double x) { return Math::IsInfinite(x) && x < 0; } static inline bool _Stl_is_neg_nan(double x) { return Math::IsNaN(x) && x < 0; } # else // nothing from above # define USE_SPRINTF_INSTEAD # endif #endif // !USE_SPRINTF_INSTEAD #if !defined (USE_SPRINTF_INSTEAD) // Reentrant versions of floating-point conversion functions. The argument // lists look slightly different on different operating systems, so we're // encapsulating the differences here. # if defined (__CYGWIN__) || defined(__DJGPP) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return ecvtbuf(x, n, pt, sign, buf); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return fcvtbuf(x, n, pt, sign, buf); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return ecvtbuf(x, n, pt, sign, buf); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return fcvtbuf(x, n, pt, sign, buf); } # endif # elif defined (__SYMBIAN32__) static inline char* _Stl_ecvtR(long double x, int n, int* pt, int* sign, char* buf) { return _symbian_ecvt(x, n, pt, sign, buf); } static inline char* _Stl_fcvtR(long double x, int n, int* pt, int* sign, char* buf) { return _symbian_fcvt(x, n, pt, sign, buf); } # elif defined (_STLP_USE_GLIBC) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return buf + ecvt_r(x, n, pt, sign, buf, NDIG+2); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return buf + fcvt_r(x, n, pt, sign, buf, NDIG+2); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return buf + qecvt_r(x, n, pt, sign, buf, NDIG+2); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return buf + qfcvt_r(x, n, pt, sign, buf, NDIG+2); } # endif # elif defined (_STLP_SCO_OPENSERVER) || defined (__NCR_SVR) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return ecvt(x, n, pt, sign); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return fcvt(x, n, pt, sign); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return ecvtl(x, n, pt, sign); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return fcvtl(x, n, pt, sign); } # endif # elif defined (__sun) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return econvert(x, n, pt, sign, buf); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return fconvert(x, n, pt, sign, buf); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return qeconvert(&x, n, pt, sign, buf); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return qfconvert(&x, n, pt, sign, buf); } # endif # elif defined (__DECCXX) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return (ecvt_r(x, n, pt, sign, buf, NDIG)==0 ? buf : 0); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return (fcvt_r(x, n, pt, sign, buf, NDIG)==0 ? buf : 0); } # if !defined (_STLP_NO_LONG_DOUBLE) // fbp : no "long double" conversions ! static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return (ecvt_r((double)x, n, pt, sign, buf, NDIG)==0 ? buf : 0) ; } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return (fcvt_r((double)x, n, pt, sign, buf, NDIG)==0 ? buf : 0); } # endif # elif defined (__hpux) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return ecvt(x, n, pt, sign); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return fcvt(x, n, pt, sign); } # if !defined (_STLP_NO_LONG_DOUBLE) # if defined( _REENTRANT ) && (defined(_PTHREADS_DRAFT4) || defined(PTHREAD_THREADS_MAX)) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return (_ldecvt_r(*(long_double*)&x, n, pt, sign, buf, NDIG+2)==0 ? buf : 0); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return (_ldfcvt_r(*(long_double*)&x, n, pt, sign, buf, NDIG+2)==0 ? buf : 0); } # else static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return _ldecvt(*(long_double*)&x, n, pt, sign); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return _ldfcvt(*(long_double*)&x, n, pt, sign); } # endif # endif # elif defined (_AIX) || defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { LOCK_CVT RETURN_CVT(ecvt, x, n, pt, sign, buf) } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { LOCK_CVT RETURN_CVT(fcvt, x, n, pt, sign, buf) } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { LOCK_CVT RETURN_CVT(ecvt, x, n, pt, sign, buf) } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { LOCK_CVT RETURN_CVT(fcvt, x, n, pt, sign, buf) } # endif # elif defined (__unix) && !defined (__APPLE__) && !defined (_CRAY) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return ecvt_r(x, n, pt, sign, buf); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return fcvt_r(x, n, pt, sign, buf); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return qecvt_r(x, n, pt, sign, buf); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return qfcvt_r(x, n, pt, sign, buf); } # endif # elif defined (_STLP_MSVC_LIB) || defined (__MINGW32__) || defined (__BORLANDC__) // those guys claim _cvt functions being reentrant. # if defined (_STLP_USE_SAFE_STRING_FUNCTIONS) # define _STLP_APPEND(a, b) a##b # define _STLP_BUF_PARAMS , char* buf, size_t bsize # define _STLP_SECURE_FUN(F, X, N, PT, SIGN) _STLP_APPEND(F, _s)(buf, bsize, X, N, PT, SIGN); return buf # else # define _STLP_CVT_DONT_NEED_BUF # define _STLP_BUF_PARAMS # define _STLP_SECURE_FUN(F, X, N, PT, SIGN) return F(X, N, PT, SIGN) # endif static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign _STLP_BUF_PARAMS) { _STLP_SECURE_FUN(_ecvt, x, n, pt, sign); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign _STLP_BUF_PARAMS) { _STLP_SECURE_FUN(_fcvt, x, n, pt, sign); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign _STLP_BUF_PARAMS) { _STLP_SECURE_FUN(_ecvt, (double)x, n, pt, sign); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign _STLP_BUF_PARAMS) { _STLP_SECURE_FUN(_fcvt, (double)x, n, pt, sign); } # endif # undef _STLP_SECURE_FUN # undef _STLP_BUF_PARAMS # undef _STLP_APPEND # elif defined (__ISCPP__) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* buf) { return _fp_ecvt( x, n, pt, sign, buf); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* buf) { return _fp_fcvt(x, n, pt, sign, buf); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* buf) { return _fp_ecvt( x, n, pt, sign, buf); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* buf) { return _fp_fcvt(x, n, pt, sign, buf); } # endif # elif defined (__MRC__) || defined (__SC__) || defined (_CRAY) static inline char* _Stl_ecvtR(double x, int n, int* pt, int* sign, char* ) { return ecvt( x, n, pt, sign ); } static inline char* _Stl_fcvtR(double x, int n, int* pt, int* sign, char* ) { return fcvt(x, n, pt, sign); } # if !defined (_STLP_NO_LONG_DOUBLE) static inline char* _Stl_qecvtR(long double x, int n, int* pt, int* sign, char* ) { return ecvt( x, n, pt, sign ); } static inline char* _Stl_qfcvtR(long double x, int n, int* pt, int* sign, char* ) { return fcvt(x, n, pt, sign); } # endif # endif # if defined (_STLP_CVT_DONT_NEED_BUF) # define _STLP_CVT_BUFFER(B) # elif !defined (_STLP_USE_SAFE_STRING_FUNCTIONS) # define _STLP_CVT_BUFFER(B) , B # else # define _STLP_CVT_BUFFER(B) , _STLP_ARRAY_AND_SIZE(B) # endif # if !defined (_STLP_USE_SAFE_STRING_FUNCTIONS) # define _STLP_BUFFER(B) B # else # define _STLP_BUFFER(B) _STLP_ARRAY_AND_SIZE(B) # endif //---------------------------------------------------------------------- // num_put // __format_float formats a mantissa and exponent as returned by // one of the conversion functions (ecvt_r, fcvt_r, qecvt_r, qfcvt_r) // according to the specified precision and format flags. This is // based on doprnt but is much simpler since it is concerned only // with floating point input and does not consider all formats. It // also does not deal with blank padding, which is handled by // __copy_float_and_fill. static size_t __format_float_scientific( __iostring& buf, const char *bp, int decpt, int sign, bool is_zero, ios_base::fmtflags flags, int precision, bool /* islong */) { // sign if required if (sign) buf += '-'; else if (flags & ios_base::showpos) buf += '+'; // first digit of mantissa buf += *bp++; // start of grouping position, grouping won't occur in scientific notation // as it is impossible to have something like 1234.0e04 but we return a correct // group position for coherency with __format_float_fixed. size_t __group_pos = buf.size(); // decimal point if required if (precision != 0 || flags & ios_base::showpoint) { buf += '.'; } // rest of mantissa int rz = precision; while (rz-- > 0 && *bp != 0) buf += *bp++; // exponent char expbuf[MAXESIZ + 2]; char *suffix = expbuf + MAXESIZ; *suffix = 0; if (!is_zero) { int nn = decpt - 1; if (nn < 0) nn = -nn; for (; nn > 9; nn /= 10) *--suffix = (char) todigit(nn % 10); *--suffix = (char) todigit(nn); } // prepend leading zeros to exponent while (suffix > &expbuf[MAXESIZ - 2]) *--suffix = '0'; // put in the exponent sign *--suffix = (char) ((decpt > 0 || is_zero ) ? '+' : '-'); // put in the e *--suffix = flags & ios_base::uppercase ? 'E' : 'e'; // copy the suffix buf += suffix; return __group_pos; } static size_t __format_float_fixed( __iostring &buf, const char *bp, int decpt, int sign, bool /* x */, ios_base::fmtflags flags, int precision, bool islong ) { if ( sign && (decpt > -precision) && (*bp != 0) ) buf += '-'; else if ( flags & ios_base::showpos ) buf += '+'; int k = 0; int maxfsig = islong ? 2*MAXFSIG : MAXFSIG; // digits before decimal point int nnn = decpt; do { buf += ((nnn <= 0 || *bp == 0 || k >= maxfsig) ? '0' : (++k, *bp++)); } while ( --nnn > 0 ); // start of grouping position size_t __group_pos = buf.size(); // decimal point if needed if ( flags & ios_base::showpoint || precision > 0 ) { buf += '.'; } // digits after decimal point if any nnn = (min) (precision, MAXFCVT); while ( --nnn >= 0 ) { buf += (++decpt <= 0 || *bp == 0 || k >= maxfsig) ? '0' : (++k, *bp++); } // trailing zeros if needed if ( precision > MAXFCVT ) { buf.append( precision - MAXFCVT, '0' ); } return __group_pos; } static void __format_nan_or_inf(__iostring& buf, double x, ios_base::fmtflags flags) { static const char* inf[2] = { "inf", "Inf" }; static const char* nan[2] = { "nan", "NaN" }; const char** inf_or_nan; if (_Stl_is_inf(x)) { // Infinity inf_or_nan = inf; if (_Stl_is_neg_inf(x)) buf += '-'; else if (flags & ios_base::showpos) buf += '+'; } else { // NaN inf_or_nan = nan; if (_Stl_is_neg_nan(x)) buf += '-'; else if (flags & ios_base::showpos) buf += '+'; } buf += inf_or_nan[flags & ios_base::uppercase ? 1 : 0]; } template <class max_double_type> static inline size_t __format_float( __iostring &buf, const char * bp, int decpt, int sign, max_double_type x, ios_base::fmtflags flags, int precision, bool islong) { size_t __group_pos = 0; // Output of infinities and NANs does not depend on the format flags if (_Stl_is_nan_or_inf((double)x)) { // Infinity or NaN __format_nan_or_inf(buf, (double)x, flags); } else { // representable number switch (flags & ios_base::floatfield) { case ios_base::scientific: __group_pos = __format_float_scientific( buf, bp, decpt, sign, x == 0.0, flags, precision, islong); break; case ios_base::fixed: __group_pos = __format_float_fixed( buf, bp, decpt, sign, true, flags, precision, islong); break; default: // g format // establish default precision if (flags & ios_base::showpoint || precision > 0) { if (precision == 0) precision = 1; } else precision = 6; // reset exponent if value is zero if (x == 0) decpt = 1; int kk = precision; if (!(flags & ios_base::showpoint)) { size_t n = strlen(bp); if (n < (size_t)kk) kk = (int)n; while (kk >= 1 && bp[kk-1] == '0') --kk; } if (decpt < -3 || decpt > precision) { precision = kk - 1; __group_pos = __format_float_scientific( buf, bp, decpt, sign, x == 0, flags, precision, islong); } else { precision = kk - decpt; __group_pos = __format_float_fixed( buf, bp, decpt, sign, true, flags, precision, islong); } break; } /* switch */ } /* else is_nan_or_inf */ return __group_pos; } #else /* USE_SPRINTF_INSTEAD */ struct GroupPos { bool operator () (char __c) const { return __c == '.' || __c == 'e' || __c == 'E'; } }; // Creates a format string for sprintf() static int __fill_fmtbuf(char* fmtbuf, ios_base::fmtflags flags, char long_modifier) { fmtbuf[0] = '%'; int i = 1; if (flags & ios_base::showpos) fmtbuf[i++] = '+'; if (flags & ios_base::showpoint) fmtbuf[i++] = '#'; fmtbuf[i++] = '.'; fmtbuf[i++] = '*'; if (long_modifier) fmtbuf[i++] = long_modifier; switch (flags & ios_base::floatfield) { case ios_base::scientific: fmtbuf[i++] = (flags & ios_base::uppercase) ? 'E' : 'e'; break; case ios_base::fixed: # if defined (__FreeBSD__) fmtbuf[i++] = 'f'; # else fmtbuf[i++] = (flags & ios_base::uppercase) ? 'F' : 'f'; # endif break; default: fmtbuf[i++] = (flags & ios_base::uppercase) ? 'G' : 'g'; break; } fmtbuf[i] = 0; return i; } #endif /* USE_SPRINTF_INSTEAD */ size_t _STLP_CALL __write_float(__iostring &buf, ios_base::fmtflags flags, int precision, double x) { #if defined (USE_SPRINTF_INSTEAD) /* If we want 'abitrary' precision, we should use 'abitrary' buffer size * below. - ptr */ char static_buf[128]; // char *static_buf = new char [128+precision]; char fmtbuf[32]; __fill_fmtbuf(fmtbuf, flags, 0); // snprintf(static_buf, 128+precision, fmtbuf, precision, x); # if !defined (N_PLAT_NLM) snprintf(_STLP_ARRAY_AND_SIZE(static_buf), fmtbuf, precision, x); # else sprintf(static_buf, fmtbuf, precision, x); # endif buf = static_buf; // delete [] static_buf; return find_if(buf.begin(), buf.end(), GroupPos()) - buf.begin(); #else # if !defined (_STLP_CVT_DONT_NEED_BUF) char cvtbuf[NDIG + 2]; # endif char * bp; int decpt, sign; switch (flags & ios_base::floatfield) { case ios_base::fixed: bp = _Stl_fcvtR(x, (min) (precision, MAXFCVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; case ios_base::scientific : bp = _Stl_ecvtR(x, (min) (precision + 1, MAXECVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; default : bp = _Stl_ecvtR(x, (min) (precision, MAXECVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; } return __format_float(buf, bp, decpt, sign, x, flags, precision, false); #endif } #if !defined (_STLP_NO_LONG_DOUBLE) size_t _STLP_CALL __write_float(__iostring &buf, ios_base::fmtflags flags, int precision, long double x) { # if defined (USE_SPRINTF_INSTEAD) /* If we want 'abitrary' precision, we should use 'abitrary' buffer size * below. - ptr */ char static_buf[128]; // char *static_buf = new char [128+precision]; char fmtbuf[64]; int i = __fill_fmtbuf(fmtbuf, flags, 'L'); // snprintf(static_buf, 128+precision, fmtbuf, precision, x); # if !defined (N_PLAT_NLM) snprintf(_STLP_ARRAY_AND_SIZE(static_buf), fmtbuf, precision, x); # else sprintf(static_buf, fmtbuf, precision, x); # endif // we should be able to return buf + sprintf(), but we do not trust'em... buf = static_buf; // delete [] static_buf; return find_if(buf.begin(), buf.end(), GroupPos()) - buf.begin(); # else # if !defined (_STLP_CVT_DONT_NEED_BUF) char cvtbuf[NDIG + 2]; # endif char * bp; int decpt, sign; switch (flags & ios_base::floatfield) { case ios_base::fixed: bp = _Stl_qfcvtR(x, (min) (precision, MAXFCVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; case ios_base::scientific: bp = _Stl_qecvtR(x, (min) (precision + 1, MAXECVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; default : bp = _Stl_qecvtR(x, (min) (precision, MAXECVT), &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); break; } return __format_float(buf, bp, decpt, sign, x, flags, precision, true); # endif /* USE_SPRINTF_INSTEAD */ } #endif /* _STLP_NO_LONG_DOUBLE */ void _STLP_CALL __get_floor_digits(__iostring &out, _STLP_LONGEST_FLOAT_TYPE __x) { #if defined (USE_SPRINTF_INSTEAD) char cvtbuf[128]; # if !defined (_STLP_NO_LONG_DOUBLE) # if !defined (N_PLAT_NLM) snprintf(_STLP_ARRAY_AND_SIZE(cvtbuf), "%Lf", __x); // check for 1234.56! # else sprintf(cvtbuf, "%Lf", __x); // check for 1234.56! # endif # else snprintf(_STLP_ARRAY_AND_SIZE(cvtbuf), "%f", __x); // check for 1234.56! # endif char *p = strchr( cvtbuf, '.' ); if ( p == 0 ) { out.append( cvtbuf ); } else { out.append( cvtbuf, p ); } #else # if !defined (_STLP_CVT_DONT_NEED_BUF) char cvtbuf[NDIG + 2]; # endif char * bp; int decpt, sign; # if !defined (_STLP_NO_LONG_DOUBLE) bp = _Stl_qfcvtR(__x, 0, &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); # else bp = _Stl_fcvtR(__x, 0, &decpt, &sign _STLP_CVT_BUFFER(cvtbuf)); # endif if (sign) { out += '-'; } out.append(bp, bp + decpt); #endif // USE_PRINTF_INSTEAD } #if !defined (_STLP_NO_WCHAR_T) void _STLP_CALL __convert_float_buffer( __iostring const& str, __iowstring &out, const ctype<wchar_t>& ct, wchar_t dot, bool __check_dot) { string::const_iterator str_ite(str.begin()), str_end(str.end()); //First loop, check the dot char if (__check_dot) { while (str_ite != str_end) { if (*str_ite != '.') { out += ct.widen(*str_ite++); } else { out += dot; break; } } } else { if (str_ite != str_end) { out += ct.widen(*str_ite); } } if (str_ite != str_end) { //Second loop, dot has been found, no check anymore while (++str_ite != str_end) { out += ct.widen(*str_ite); } } } #endif void _STLP_CALL __adjust_float_buffer(__iostring &str, char dot) { if ('.' != dot) { size_t __dot_pos = str.find('.'); if (__dot_pos != string::npos) { str[__dot_pos] = dot; } } } _STLP_MOVE_TO_STD_NAMESPACE _STLP_END_NAMESPACE // Local Variables: // mode:C++ // End:
gpl-2.0