base: DestinyCore upstream @2d631f4e (fork SylvaniaCore ; sql/old retire)

This commit is contained in:
SylvaniaCore deploy
2026-06-17 09:00:37 +00:00
commit f8fcb8ad38
4834 changed files with 2810723 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
[*]
charset = utf-8
indent_size = 4
tab_width = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 80
[*.{c,h,cpp,hpp,inl}]
charset = latin1
+31
View File
@@ -0,0 +1,31 @@
# Auto detect text files and perform LF normalization
* text=auto
# Whitespace rules
# strict (no trailing, no tabs)
*.cpp whitespace=trailing-space,space-before-tab,tab-in-indent,cr-at-eol
*.h whitespace=trailing-space,space-before-tab,tab-in-indent,cr-at-eol
# normal (no trailing)
*.sql whitespace=trailing-space,space-before-tab,cr-at-eol
*.txt whitespace=trailing-space,space-before-tab,cr-at-eol
# special files which must ignore whitespace
*.patch whitespace=-trailing-space eol=lf
*.diff whitespace=-trailing-space eol=lf
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
# Ignore sql/* files
sql/* linguist-documentation
+29
View File
@@ -0,0 +1,29 @@
---
name: 🐞 Bug Report
about: Report a problem or unexpected behavior in the game or core
title: "[Bug] "
labels: [bug]
assignees: []
---
### 📝 Description
A clear and concise description of what the bug is.
### 📍 Location
Where did the bug happen? (Map, Instance, NPC, etc.)
### 🔁 Reproduction Steps
Steps to reproduce the behavior:
1. Go to '...'
2. Do '...'
3. Observe '...'
### ✔️ Expected Behavior
What did you expect to happen?
### 🖼️ Screenshots / Videos
If applicable, add screenshots or videos.
### 🌐 Server Revision / Hash
Provide the core revision or hash you're using.
+17
View File
@@ -0,0 +1,17 @@
---
name: 💡 Feature Request
about: Suggest a new feature, enhancement, or idea
title: "[Feature] "
labels: [enhancement]
assignees: []
---
### 🚀 Summary
What would you like to see added or changed?
### 🔍 Context
Why would this feature be useful or beneficial?
### 🧩 Additional Information
Add any other context or references here.
+23
View File
@@ -0,0 +1,23 @@
---
name: 🧍 NPC Issue
about: Report an issue with an NPC (behavior, spawn, dialogue, etc.)
title: "[NPC] "
labels: [npc]
assignees: []
---
### 🧍 NPC Name or Entry ID
Provide the name and/or entry ID of the NPC.
### 📍 Location
Where is the NPC located?
### 🔁 Problem Description
Explain what's wrong with the NPC.
### 📷 Screenshot / Video
Attach visual proof if available.
### 🌐 Server Revision / Hash
Provide your server revision/hash.
+23
View File
@@ -0,0 +1,23 @@
---
name: 🧾 Quest Issue
about: Report a bug or problem related to quests
title: "[Quest] "
labels: [quest]
assignees: []
---
### 📝 Quest Name or ID
Provide the quest name and/or ID.
### 📍 Location
Where does the issue occur?
### 🔁 Problem
Describe what is wrong with the quest (missing text, can't be accepted, no rewards, etc).
### 📸 Screenshots
Add screenshots if possible.
### 🌐 Server Revision / Hash
Provide the server revision or hash.
+39
View File
@@ -0,0 +1,39 @@
name: Clang
on:
push:
branches:
- master
pull_request:
jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set reusable strings
id: strings
shell: bash
run: |
echo "build-output-dir=${{ github.workspace }}/bin" >> "$GITHUB_OUTPUT"
- name: Dependencies
run: |
sudo apt-get update && sudo apt-get install -yq libboost-all-dev clang-14
- name: Setup
env:
CMAKE_BUILD_TYPE: Debug
run: >
cmake -S ${{ github.workspace }} -B ${{ steps.strings.outputs.build-output-dir }}
-DWITH_WARNINGS=1 -DWITH_WARNINGS_AS_ERRORS=0 -DWITH_COREDEBUG=0 -DUSE_COREPCH=1 -DUSE_SCRIPTPCH=1 -DTOOLS=1 -DSCRIPTS=dynamic -DSERVERS=1 -DNOJEM=0
-DCMAKE_C_FLAGS_DEBUG="-DNDEBUG" -DCMAKE_CXX_FLAGS_DEBUG="-DNDEBUG"
-DCMAKE_INSTALL_PREFIX=check_install
-DCMAKE_C_COMPILER=/usr/bin/clang -DCMAKE_CXX_COMPILER=/usr/bin/clang++
- name: Build
run: |
cd bin
make -j 4 -k && make install
- name: Check executables
run: |
cd ${{ github.workspace }}/check_install/bin
./bnetserver --version
./worldserver --version
+39
View File
@@ -0,0 +1,39 @@
name: GCC
on:
push:
branches:
- master
pull_request:
jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set reusable strings
id: strings
shell: bash
run: |
echo "build-output-dir=${{ github.workspace }}/bin" >> "$GITHUB_OUTPUT"
- name: Dependencies
run: |
sudo apt-get update && sudo apt-get install -yq libboost-all-dev g++-11
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100 --slave /usr/bin/g++ g++ /usr/bin/g++-11
- name: Setup
env:
CMAKE_BUILD_TYPE: Debug
run: >
cmake -S ${{ github.workspace }} -B ${{ steps.strings.outputs.build-output-dir }}
-DWITH_WARNINGS=1 -DWITH_WARNINGS_AS_ERRORS=0 -DWITH_COREDEBUG=0 -DUSE_COREPCH=1 -DUSE_SCRIPTPCH=1 -DTOOLS=1 -DSCRIPTS=dynamic -DSERVERS=1 -DNOJEM=0
-DCMAKE_C_FLAGS_DEBUG="-DNDEBUG" -DCMAKE_CXX_FLAGS_DEBUG="-DNDEBUG"
-DCMAKE_INSTALL_PREFIX=check_install
- name: Build
run: |
cd bin
make -j 4 -k && make install
- name: Check executables
run: |
cd ${{ github.workspace }}/check_install/bin
./bnetserver --version
./worldserver --version
+106
View File
@@ -0,0 +1,106 @@
name: Windows x64
on:
push:
branches:
- master
pull_request:
jobs:
build:
runs-on: windows-latest
env:
CMAKE_BUILD_TYPE: RelWithDebInfo
MYSQL_ROOT_DIR: C:/Program Files/MySQL/MySQL Server 8.0
OPENSSL_ROOT_DIR: C:/libs/openssl
steps:
- uses: actions/checkout@v4
- name: Set reusable strings
id: strings
shell: bash
run: |
echo "build-output-dir=${{ github.workspace }}/build" >> "$GITHUB_OUTPUT"
- name: Get current OpenSSL version
id: openssl-info
run: |
$VersionsUrl = "https://api.github.com/repos/slproweb/opensslhashes/contents/win32_openssl_hashes.json"
$Headers = @{
Accept="application/vnd.github.raw+json"
Authorization="Bearer ${{ secrets.GITHUB_TOKEN }}"
}
$openSSL = (Invoke-RestMethod $VersionsUrl -Headers $Headers).files.PSObject.Properties |
Select-Object -ExpandProperty Value |
Where-Object { $_.arch -eq 'INTEL' } |
Where-Object { $_.bits -eq '64' } |
Where-Object { $_.light -eq $false } |
Where-Object { $_.installer -eq 'exe' } |
Where-Object { $_.basever -like '3.*' } |
Sort-Object -Descending @{ Expression = { [version]$_.basever } } |
Select-Object -First 1
[System.String]::Format("cache-key=openssl-{0}-win-{1}-{2}", $openSSL.basever, $openSSL.arch, $openSSL.bits) >> $env:GITHUB_OUTPUT
[System.String]::Format("url={0}", $openSSL.url) >> $env:GITHUB_OUTPUT
- name: Cache OpenSSL
id: cache-openssl
uses: actions/cache@v4
with:
path: ${{ env.OPENSSL_ROOT_DIR }}
key: ${{ steps.openssl-info.outputs.cache-key }}
- name: Download and install Openssl 3.x
if: ${{ steps.cache-openssl.outputs.cache-hit != 'true' }}
run: |
(New-Object System.Net.WebClient).DownloadFile("${{ steps.openssl-info.outputs.url }}", "${{ env.TEMP }}\openssl.exe")
Start-Process -Wait -FilePath "${{ env.TEMP }}\openssl.exe" "/SILENT","/SP-","/SUPPRESSMSGBOXES",/DIR=${{ env.OPENSSL_ROOT_DIR }}
# Quick Openssl install test
& ${{ env.OPENSSL_ROOT_DIR }}/bin/openssl.exe version
- name: Download and install Boost
uses: MarkusJx/install-boost@6d8df42f57de83c5b326b5b83e7b35d650030103
id: install-boost
with:
boost_version: 1.84.0
link: static
platform_version: 2022
toolset: msvc
- name: Initialize Visual Studio Environment
uses: egor-tensin/vs-shell@v2
with:
arch: x64
- name: Configure CMake
env:
BOOST_ROOT: ${{ steps.install-boost.outputs.BOOST_ROOT }}
run: >
cmake -GNinja -S ${{ github.workspace }} -B ${{ steps.strings.outputs.build-output-dir }}
-DTOOLS=ON
- name: Build
run: |
cmake --build ${{ steps.strings.outputs.build-output-dir }}
- name: Copy Dependencies
run: |
cd ${{ steps.strings.outputs.build-output-dir }}/bin/${{ env.CMAKE_BUILD_TYPE }}
copy "${{ env.MYSQL_ROOT_DIR }}/lib/libmysql.dll" libmysql.dll
copy "${{ env.OPENSSL_ROOT_DIR }}/bin/libssl-3-x64.dll" libssl-3-x64.dll
copy "${{ env.OPENSSL_ROOT_DIR }}/bin/libcrypto-3-x64.dll" libcrypto-3-x64.dll
copy "${{ env.OPENSSL_ROOT_DIR }}/bin/legacy.dll" legacy.dll
- name: Check binaries
run: |
cd ${{ steps.strings.outputs.build-output-dir }}/bin/${{ env.CMAKE_BUILD_TYPE }}
./bnetserver --version
./worldserver --version
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
path: ${{ steps.strings.outputs.build-output-dir }}/bin/${{ env.CMAKE_BUILD_TYPE }}
name: DestinyCoreMasterWin64VS2022
# Set a custom retention for artifacts
#retention-days: 7
+25
View File
@@ -0,0 +1,25 @@
build*/
.directory
.mailmap
*.orig
*.rej
*~
.hg/
*.kdev*
.DS_Store
CMakeLists.txt.user
*.bak
*.patch
*.diff
*.REMOTE.*
*.BACKUP.*
*.BASE.*
*.LOCAL.*
nbproject/*
.idea/*
.browse.VC*
.vscode
cmake-build-*/
.vs
/build/
+60
View File
@@ -0,0 +1,60 @@
sudo: false
dist: trusty
language: cpp
compiler:
- clang
git:
depth: 1
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- sourceline: 'ppa:kzemek/boost'
packages:
- g++-6
- libboost1.58-dev
- libboost-filesystem1.58-dev
- libboost-iostreams1.58-dev
- libboost-program-options1.58-dev
- libboost-regex1.58-dev
- libboost-system1.58-dev
- libboost-thread1.58-dev
- libssl-dev
- libmysqlclient-dev
- libreadline6-dev
- zlib1g-dev
- libbz2-dev
services:
- mysql
before_install:
- git config user.email "travis@build.bot" && git config user.name "Travis CI"
- git tag -a -m "Travis build" init
install:
- mysql -uroot -e 'create database test_mysql;'
- mkdir bin
- cd bin
- cmake ../ -DWITH_WARNINGS=1 -DWITH_COREDEBUG=0 -DUSE_COREPCH=1 -DUSE_SCRIPTPCH=1 -DTOOLS=1 -DSCRIPTS=dynamic -DSERVERS=1 -DNOJEM=1 -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="-Werror" -DCMAKE_CXX_FLAGS="-Werror" -DCMAKE_C_FLAGS_DEBUG="-DNDEBUG" -DCMAKE_CXX_FLAGS_DEBUG="-DNDEBUG" -DCMAKE_INSTALL_PREFIX=check_install -DWITH_CPR=1
- cd ..
- chmod +x contrib/check_updates.sh
script:
- $CXX --version
- mysql -uroot < sql/create/create_mysql.sql
- mysql -utrinity -ptrinity auth < sql/base/auth_database.sql
- mysql -utrinity -ptrinity characters < sql/base/characters_database.sql
- mysql -utrinity -ptrinity world < sql/base/dev/world_database.sql
- mysql -utrinity -ptrinity hotfixes < sql/base/dev/hotfixes_database.sql
- cat sql/updates/world/master/*.sql | mysql -utrinity -ptrinity world
- cat sql/updates/hotfixes/master/*.sql | mysql -utrinity -ptrinity hotfixes
- mysql -uroot < sql/create/drop_mysql.sql
- cd bin
- make -j 4 -k && make install
- cd check_install/bin
- ./bnetserver --version
- ./worldserver --version
+84
View File
@@ -0,0 +1,84 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
cmake_minimum_required(VERSION 3.24)
# add this options before PROJECT keyword
set(CMAKE_DISABLE_SOURCE_CHANGES ON)
set(CMAKE_DISABLE_IN_SOURCE_BUILD ON)
# Set projectname (must be done AFTER setting configurationtypes)
project(DestinyCore)
if(POLICY CMP0144)
cmake_policy(SET CMP0144 NEW) # find_package() uses upper-case <PACKAGENAME>_ROOT variables
endif()
if(POLICY CMP0153)
cmake_policy(SET CMP0153 NEW) # The exec_program() command should not be called
endif()
# Set RPATH-handing (CMake parameters)
set(CMAKE_SKIP_BUILD_RPATH 0)
set(CMAKE_BUILD_WITH_INSTALL_RPATH 0)
list(APPEND CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH 1)
# set macro-directory
list(APPEND CMAKE_MODULE_PATH
"${CMAKE_SOURCE_DIR}/cmake/macros")
# build in Release-mode by default if not explicitly set
if(CMAKE_GENERATOR STREQUAL "Ninja Multi-Config")
set(CMAKE_DEFAULT_BUILD_TYPE "RelWithDebInfo" CACHE INTERNAL "")
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "RelWithDebInfo")
endif()
include(CheckCXXSourceRuns)
include(CheckIncludeFiles)
include(ConfigureScripts)
# set default buildoptions and print them
include(cmake/options.cmake)
# turn off PCH totally if enabled (hidden setting, mainly for devs)
if(NOPCH)
set(USE_COREPCH 0)
set(USE_SCRIPTPCH 0)
endif()
include(ConfigureBaseTargets)
include(CheckPlatform)
include(GroupSources)
include(AutoCollect)
find_package(PCHSupport)
if(NOT WITHOUT_GIT)
find_package(Git)
endif()
# find mysql client binary (needed by genrev)
find_package(MySQL OPTIONAL_COMPONENTS binary)
# Find revision ID and hash of the sourcetree
include(cmake/genrev.cmake)
# print out the results before continuing
include(cmake/showoptions.cmake)
# add dependencies
add_subdirectory(dep)
# add core sources
add_subdirectory(src)
+69
View File
@@ -0,0 +1,69 @@
# Contributing
So, you want to contribute? Great!
Contributing is not only about creating fixes, but also reporting bugs. Before reporting a bug, please make sure to use the latest core and database revision.
Issues
======
Read [this](https://www.trinitycore.org/f/topic/37-the-trinitycore-issuetracker-and-you/) before creating a ticket.
If you have problems with TrinityCore installation, read [this](https://www.trinitycore.org/f/topic/1518-trouble-with-your-trinity-install-readme-1st-faqs/).
Mandatory things when creating a ticket:
========================================
- Branch
- commit hash (if you get something like TrinityCore rev. unknown 1970-01-01 00:00:00 +0000 (Archived branch) (Win64, Release), please read this [post](https://www.trinitycore.org/f/topic/345-howto-properly-install-git-on-windows-fix-trinitycore-rev-1970-01-01-000000-0000/) or clone this repository instead downloading the source code.
- entries of affected creatures / items / quests with a link to the relevant wowhead page.
- clear title and description of the bug - if your english is very bad, please use google translate or yandex to translate to english and include one text in your native language.
When reporting a crash, you MUST compile in debug mode because release dumps are useless (not enough information) - if you don't know how to compile in debug, read [this](https://www.trinitycore.org/f/topic/1518-trouble-with-your-trinity-install-readme-1st-faqs/#entry47672)
We sugest the title and body to have the next style:
DB/Quest: The Collapse
4.3.4 branch
hash 63f96a282307
The quest "The Collapse" http://www.wowhead.com/quest=11706 lacks final event.
Creating Pull Requests:
=======================
1. Fork it.
2. Create a branch (`git checkout -b fixes`) (Note: fixes is an arbitrary name, choose whatever you want here)
3. Commit your changes (`git commit -am "Added Snarkdown"`)
4. Push to the branch (`git push origin fixes`)
5. Open a Pull Request
When creating patches read:
- [TrinityCore Development Standards](https://www.trinitycore.org/f/topic/6-trinitycore-developing-standards/)
- [WDB Fields](https://www.trinitycore.org/f/topic/58-wdb-fields/)
- [Git Squash](https://ariejan.net/2011/07/05/git-squash-your-latests-commits-into-one/)
We suggest that you create one branch for each C++ based fix: this will allow you to create more fixes without having to wait for your pull request to be merged.
For the SQL files coming with C++ based fixes the naming schema is `YYYY_MM_DD_i_database.sql`, where `YYYY_MM_DD` is the date of the fix, `i_database` is the *ith* sql created that day for `database`.
When doing changes to `auth` or `characters` database remember to update the base files (`/sql/base/*`).
For SQL only fixes, please [create a ticket](https://github.com/TrinityCore/TrinityCore/issues/new).
Since it's very unlikely that your Pull Request will be merged on the day that you open it, please name the files with an impossible date to avoid merging issues ie: 2015_13_32_00_world.sql
Wiki
====
The wiki is located at [https://trinitycore.info](https://trinitycore.info).
You are welcome to create an account and help us improve and extend the wiki.
Requirements
============
Software requirements are available in the [wiki](https://www.trinitycore.info/display/tc/Requirements) for
Windows, Linux and Mac OSX.
If you choose Linux, we recommend to use Debian 8, since it's the Linux that we use to test compilations.
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+6
View File
@@ -0,0 +1,6 @@
For installation instructions read www.trinitycore.info
Remember that TrinityCore needs sse2 capable processor as well c++11 compiler.
If you still have installation problems check:
https://www.trinitycore.org/f/topic/10656-updating-or-starting-with-trinitycore-issues/
https://www.trinitycore.org/f/topic/1518-trouble-with-your-trinity-install-readme-1st-faqs/
+23
View File
@@ -0,0 +1,23 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# This file is run right before CMake starts configuring the sourcetree
# Example: Force CMAKE_INSTALL_PREFIX to be preloaded with something before
# doing the actual first "configure"-part - allows for hardforcing
# destinations elsewhere in the CMake buildsystem (commented out on purpose)
# Override CMAKE_INSTALL_PREFIX on Windows platforms
#if( WIN32 )
# if( NOT CYGWIN )
# set(CMAKE_INSTALL_PREFIX
# "" CACHE PATH "Default install path")
# endif()
#endif()
+103
View File
@@ -0,0 +1,103 @@
# DestinyCore
[![License: GPL v2](https://img.shields.io/badge/License-GPLv2-blue.svg)](./LICENSE)
[![Stars](https://img.shields.io/github/stars/slash-design/DestinyCore.svg?style=flat&logo=github)](https://github.com/slash-design/DestinyCore/stargazers)
[![Forks](https://img.shields.io/github/forks/slash-design/DestinyCore.svg?style=flat&logo=github)](https://github.com/slash-design/DestinyCore/network/members)
---
## 🚀 Build Status
Windows | GCC | Clang
:------------: | :------------: | :------------:
[![Windows x64](https://github.com/slash-design/DestinyCore/actions/workflows/win-x64-build.yml/badge.svg)](https://github.com/slash-design/DestinyCore/actions/workflows/win-x64-build.yml) | [![GCC](https://github.com/slash-design/DestinyCore/actions/workflows/gcc-build.yml/badge.svg)](https://github.com/slash-design/DestinyCore/actions/workflows/gcc-build.yml) | [![Clang](https://github.com/slash-design/DestinyCore/actions/workflows/clang-build.yml/badge.svg)](https://github.com/slash-design/DestinyCore/actions/workflows/clang-build.yml)
---
## 📖 Introduction
**DestinyCore** is a modern, modular **MMORPG server framework** written in C++ that supports **multiple platforms** (Windows, Linux, macOS) and builds cleanly with **GCC, Clang, and MSVC**.
It is designed to be **lightweight, scalable, and extensible**, providing developers and server administrators with a stable foundation for World of Warcraft® (Legion 7.3.5) and beyond.
Key goals of DestinyCore:
- ⚡ Modern C++ design (C++20+)
- 🔌 Modular architecture (authserver, worldserver, shared libs)
- 🤖 Integrated **PlayerBots** system
- 🌍 Multi-database support (auth, characters, world)
- 🛠️ Easy build system (CMake + GitHub Actions CI)
- 🎮 MMO-ready networking with scalability in mind
---
## 🛠️ Requirements
DestinyCore depends on modern development tools and libraries:
- **CMake 3.31+**
- **Boost 1.84.0**
- **MySQL 8.0**
- **OpenSSL 3.x**
- **GCC / Clang / MSVC (Visual Studio 2022 recommended)**
---
## 📦 Installation
1. Clone the repository:
```bash
git clone https://github.com/slash-design/DestinyCore.git
cd DestinyCore
```
2. Create a build directory:
```bash
cmake -S . -B build -DTOOLS=ON
cmake --build build
```
3. Configure your databases (`auth`, `characters`, `world`) and import the SQL structures provided in `/sql/base`.
4. Start the servers:
```bash
./bin/worldserver
./bin/bnetserver
```
---
## 🤝 Contributing
We welcome all contributions!
Whether you’re fixing a bug, improving documentation, or adding new features — PRs are always appreciated.
- Fork the repo
- Create a feature branch
- Submit a pull request
---
## 🐛 Reporting Issues
Issues can be reported directly via the [GitHub Issue Tracker](https://github.com/slash-design/DestinyCore/issues).
Before creating a new one, please check for existing reports to avoid duplicates.
---
## 📜 License
This project is licensed under **GPL v2.0**.
See the [LICENSE](./LICENSE) file for details.
---
## 🌐 Links
- 📂 [GitHub Repository](https://github.com/slash-design/DestinyCore)
- 📌 [Issues](https://github.com/slash-design/DestinyCore/issues)
- 📖 [Documentation (WIP)](https://github.com/slash-design/DestinyCore/wiki)
---
⭐ If you like DestinyCore, consider giving the project a star on GitHub!
+1016
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
# Set build-directive (used in core to tell which buildtype we used)
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$<CONFIG>")
if(WITH_WARNINGS)
target_compile_options(trinity-warning-interface
INTERFACE
-W
-Wall
-Wextra
-Winit-self
-Wfatal-errors
-Wno-mismatched-tags
-Woverloaded-virtual)
message(STATUS "Clang: All warnings enabled")
endif()
if(WITH_COREDEBUG)
target_compile_options(trinity-compile-option-interface
INTERFACE
-g3)
message(STATUS "Clang: Debug-flags set (-g3)")
endif()
# -Wno-narrowing needed to suppress a warning in g3d
# -Wno-deprecated-register is needed to suppress 185 gsoap warnings on Unix systems.
target_compile_options(trinity-compile-option-interface
INTERFACE
-Wno-narrowing
-Wno-deprecated-register)
if (BUILD_SHARED_LIBS)
# -fPIC is needed to allow static linking in shared libs.
# -fvisibility=hidden sets the default visibility to hidden to prevent exporting of all symbols.
target_compile_options(trinity-compile-option-interface
INTERFACE
-fPIC)
target_compile_options(trinity-hidden-symbols-interface
INTERFACE
-fvisibility=hidden)
# --no-undefined to throw errors when there are undefined symbols
# (caused through missing TRINITY_*_API macros).
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --no-undefined")
message(STATUS "Clang: Disallow undefined symbols")
endif()
+63
View File
@@ -0,0 +1,63 @@
# Set build-directive (used in core to tell which buildtype we used)
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$<CONFIG>")
set(GCC_EXPECTED_VERSION 6.3.0)
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS GCC_EXPECTED_VERSION)
message(FATAL_ERROR "GCC: TrinityCore requires version ${GCC_EXPECTED_VERSION} to build but found ${CMAKE_CXX_COMPILER_VERSION}")
endif()
if(PLATFORM EQUAL 32)
# Required on 32-bit systems to enable SSE2 (standard on x64)
target_compile_options(trinity-compile-option-interface
INTERFACE
-msse2
-mfpmath=sse)
endif()
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-DHAVE_SSE2
-D__SSE2__)
message(STATUS "GCC: SFMT enabled, SSE2 flags forced")
if( WITH_WARNINGS )
target_compile_options(trinity-warning-interface
INTERFACE
-W
-Wall
-Wextra
-Winit-self
-Winvalid-pch
-Wfatal-errors
-Woverloaded-virtual)
message(STATUS "GCC: All warnings enabled")
endif()
if( WITH_COREDEBUG )
target_compile_options(trinity-compile-option-interface
INTERFACE
-g3)
message(STATUS "GCC: Debug-flags set (-g3)")
endif()
if (BUILD_SHARED_LIBS)
target_compile_options(trinity-compile-option-interface
INTERFACE
-fPIC
-Wno-attributes)
target_compile_options(trinity-hidden-symbols-interface
INTERFACE
-fvisibility=hidden)
# Should break the build when there are TRINITY_*_API macros missing
# but it complains about missing references in precompiled headers.
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,--no-undefined")
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-undefined")
message(STATUS "GCC: Enabled shared linking")
endif()
+28
View File
@@ -0,0 +1,28 @@
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$<CONFIG>")
if(PLATFORM EQUAL 32)
target_compile_options(trinity-compile-option-interface
INTERFACE
-axSSE2)
else()
target_compile_options(trinity-compile-option-interface
INTERFACE
-xSSE2)
endif()
if( WITH_WARNINGS )
target_compile_options(trinity-warning-interface
INTERFACE
-w1)
message(STATUS "ICC: All warnings enabled")
endif()
if( WITH_COREDEBUG )
target_compile_options(trinity-compile-option-interface
INTERFACE
-g)
message(STATUS "ICC: Debug-flag set (-g)")
endif()
+39
View File
@@ -0,0 +1,39 @@
# Set build-directive (used in core to tell which buildtype we used)
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$<CONFIG>")
if(PLATFORM EQUAL 32)
# Required on 32-bit systems to enable SSE2 (standard on x64)
target_compile_options(trinity-compile-option-interface
INTERFACE
-msse2
-mfpmath=sse)
endif()
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-DHAVE_SSE2
-D__SSE2__)
message(STATUS "GCC: SFMT enabled, SSE2 flags forced")
if( WITH_WARNINGS )
target_compile_options(trinity-warning-interface
INTERFACE
-W
-Wall
-Wextra
-Winit-self
-Winvalid-pch
-Wfatal-errors
-Woverloaded-virtual)
message(STATUS "GCC: All warnings enabled")
endif()
if( WITH_COREDEBUG )
target_compile_options(trinity-compile-option-interface
INTERFACE
-g3)
message(STATUS "GCC: Debug-flags set (-g3)")
endif()
@@ -0,0 +1,6 @@
<Project>
<PropertyGroup>
<UseMultiToolTask>false</UseMultiToolTask>
<UseMSBuildResourceManager>false</UseMSBuildResourceManager>
</PropertyGroup>
</Project>
+174
View File
@@ -0,0 +1,174 @@
set(MSVC_EXPECTED_VERSION 19.24)
set(MSVC_EXPECTED_VERSION_STRING "Microsoft Visual Studio 2019 16.4")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MSVC_EXPECTED_VERSION)
message(FATAL_ERROR "MSVC: DestinyCore requires version ${MSVC_EXPECTED_VERSION} (${MSVC_EXPECTED_VERSION_STRING}) to build but found ${CMAKE_CXX_COMPILER_VERSION}")
endif()
# CMake sets warning flags by default, however we manage it manually
# for different core and dependency targets
string(REGEX REPLACE "/W[0-4] " "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
# Search twice, once for space after /W argument,
# once for end of line as CMake regex has no \b
string(REGEX REPLACE "/W[0-4]$" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
string(REGEX REPLACE "/W[0-4] " "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
string(REGEX REPLACE "/W[0-4]$" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
target_compile_options(trinity-warning-interface
INTERFACE
/W3)
# disable permissive mode to make msvc more eager to reject code that other compilers don't already accept
target_compile_options(trinity-compile-option-interface
INTERFACE
/permissive-)
# set up output paths ofr static libraries etc (commented out - shown here as an example only)
#set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
#set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
if(PLATFORM EQUAL 64)
# This definition is necessary to work around a bug with Intellisense described
# here: http://tinyurl.com/2cb428. Syntax highlighting is important for proper
# debugger functionality.
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_WIN64)
message(STATUS "MSVC: 64-bit platform, enforced -D_WIN64 parameter")
else()
# mark 32 bit executables large address aware so they can use > 2GB address space
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE")
message(STATUS "MSVC: Enabled large address awareness")
target_compile_options(trinity-compile-option-interface
INTERFACE
/arch:SSE2)
message(STATUS "MSVC: Enabled SSE2 support")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /SAFESEH:NO")
message(STATUS "MSVC: Disabled Safe Exception Handlers for debug builds")
endif()
# Set build-directive (used in core to tell which buildtype we used)
# msbuild/devenv don't set CMAKE_MAKE_PROGRAM, you can choose build type from a dropdown after generating projects
if("${CMAKE_MAKE_PROGRAM}" MATCHES "MSBuild")
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$(ConfigurationName)")
else()
# while all make-like generators do (nmake, ninja)
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="$<CONFIG>")
endif()
# multithreaded compiling on VS
target_compile_options(trinity-compile-option-interface
INTERFACE
/MP)
if((PLATFORM EQUAL 64) OR (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.23026.0) OR BUILD_SHARED_LIBS)
# Enable extended object support
target_compile_options(trinity-compile-option-interface
INTERFACE
/bigobj)
message(STATUS "MSVC: Enabled increased number of sections in object files")
endif()
# /Zc:throwingNew.
# When you specify Zc:throwingNew on the command line, it instructs the compiler to assume
# that the program will eventually be linked with a conforming operator new implementation,
# and can omit all of these extra null checks from your program.
# http://blogs.msdn.com/b/vcblog/archive/2015/08/06/new-in-vs-2015-zc-throwingnew.aspx
if(NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.23026.0))
# makes this flag a requirement to build TC at all
target_compile_options(trinity-compile-option-interface
INTERFACE
/Zc:throwingNew)
endif()
# Define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES - eliminates the warning by changing the strcpy call to strcpy_s, which prevents buffer overruns
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
message(STATUS "MSVC: Overloaded standard names")
# Ignore warnings about older, less secure functions
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_CRT_SECURE_NO_WARNINGS)
message(STATUS "MSVC: Disabled NON-SECURE warnings")
# Ignore warnings about POSIX deprecation
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_CRT_NONSTDC_NO_WARNINGS)
message(STATUS "MSVC: Disabled POSIX warnings")
# Ignore specific warnings
target_compile_options(trinity-compile-option-interface
INTERFACE
/wd4351 # C4351: new behavior: elements of array 'x' will be default initialized
/wd4091) # C4091: 'typedef ': ignored on left of '' when no variable is declared
if(NOT WITH_WARNINGS)
target_compile_options(trinity-compile-option-interface
INTERFACE
/wd4996 # C4996 deprecation
/wd4985 # C4985 'symbol-name': attributes not present on previous declaration.
/wd4244 # C4244 'argument' : conversion from 'type1' to 'type2', possible loss of data
/wd4267 # C4267 'var' : conversion from 'size_t' to 'type', possible loss of data
/wd4619 # C4619 #pragma warning : there is no warning number 'number'
/wd4512) # C4512 'class' : assignment operator could not be generated
message(STATUS "MSVC: Disabled generic compiletime warnings")
endif()
if (BUILD_SHARED_LIBS)
target_compile_options(trinity-compile-option-interface
INTERFACE
/wd4251 # C4251: needs to have dll-interface to be used by clients of class '...'
/wd4275) # C4275: non dll-interface class ...' used as base for dll-interface class '...'
message(STATUS "MSVC: Enabled shared linking")
endif()
# Move some warnings that are enabled for other compilers from level 4 to level 3
target_compile_options(trinity-compile-option-interface
INTERFACE
/w34100 # C4100 'identifier' : unreferenced formal parameter
/w34101 # C4101: 'identifier' : unreferenced local variable
/w34189 # C4189: 'identifier' : local variable is initialized but not referenced
/w34389) # C4189: 'equality-operator' : signed/unsigned mismatch
# Enable and treat as errors the following warnings to easily detect virtual function signature failures:
# 'function' : member function does not override any base class virtual member function
# 'virtual_function' : no override available for virtual member function from base 'class'; function is hidden
target_compile_options(trinity-compile-option-interface
INTERFACE
/we4263
/we4264)
# Disable incremental linking in debug builds.
# To prevent linking getting stuck (which might be fixed in a later VS version).
macro(DisableIncrementalLinking variable)
string(REGEX REPLACE "/INCREMENTAL *" "" ${variable} "${${variable}}")
set(${variable} "${${variable}} /INCREMENTAL:NO")
endmacro()
# Disable Visual Studio 2022 build process management
# This will make compiler behave like in 2019 - compiling num_cpus * num_projects at the same time
# it is neccessary because of a bug in current implementation that makes scripts build only a single
# file at the same time after game project finishes building
if (NOT MSVC_TOOLSET_VERSION LESS 143)
file(COPY "${CMAKE_CURRENT_LIST_DIR}/Directory.Build.props" DESTINATION "${CMAKE_BINARY_DIR}")
endif()
DisableIncrementalLinking(CMAKE_EXE_LINKER_FLAGS_DEBUG)
DisableIncrementalLinking(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO)
DisableIncrementalLinking(CMAKE_SHARED_LINKER_FLAGS_DEBUG)
DisableIncrementalLinking(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO)
+78
View File
@@ -0,0 +1,78 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# User has manually chosen to ignore the git-tests, so throw them a warning.
# This is done EACH compile so they can be alerted about the consequences.
if(NOT BUILDDIR)
# Workaround for funny MSVC behaviour - this segment is only used when using cmake gui
set(BUILDDIR ${CMAKE_BINARY_DIR})
endif()
if(WITHOUT_GIT)
set(rev_date "1970-01-01 00:00:00 +0000")
set(rev_hash "unknown")
set(rev_branch "Archived")
else()
if(GIT_EXECUTABLE)
# Create a revision-string that we can use
execute_process(
COMMAND "${GIT_EXECUTABLE}" describe --long --match init --dirty=+ --abbrev=12
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE rev_info
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
)
# And grab the commits timestamp
execute_process(
COMMAND "${GIT_EXECUTABLE}" show -s --format=%ci
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE rev_date
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
)
# Also retrieve branch name
execute_process(
COMMAND "${GIT_EXECUTABLE}" rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
OUTPUT_VARIABLE rev_branch
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
)
endif()
# Last minute check - ensure that we have a proper revision
# If everything above fails (means the user has erased the git revision control directory or removed the origin/HEAD tag)
if(NOT rev_info)
# No valid ways available to find/set the revision/hash, so let's force some defaults
message(STATUS "
Could not find a proper repository signature (hash) - you may need to pull tags with git fetch -t
Continuing anyway - note that the versionstring will be set to \"unknown 1970-01-01 00:00:00 (Archived)\"")
set(rev_date "1970-01-01 00:00:00 +0000")
set(rev_hash "unknown")
set(rev_branch "Archived")
else()
# Extract information required to build a proper versionstring
string(REGEX REPLACE init-|[0-9]+-g "" rev_hash ${rev_info})
endif()
endif()
# Create the actual revision_data.h file from the above params
if(NOT "${rev_hash_cached}" MATCHES "${rev_hash}" OR NOT "${rev_branch_cached}" MATCHES "${rev_branch}" OR NOT EXISTS "${BUILDDIR}/revision_data.h")
configure_file(
"${CMAKE_SOURCE_DIR}/revision_data.h.in.cmake"
"${BUILDDIR}/revision_data.h"
@ONLY
)
set(rev_hash_cached "${rev_hash}" CACHE INTERNAL "Cached commit-hash")
set(rev_branch_cached "${rev_branch}" CACHE INTERNAL "Cached branch name")
endif()
+71
View File
@@ -0,0 +1,71 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# Collects all source files into the given variable,
# which is useful to include all sources in subdirectories.
# Ignores full qualified directories listed in the variadic arguments.
#
# Use it like:
# CollectSourceFiles(
# ${CMAKE_CURRENT_SOURCE_DIR}
# COMMON_PRIVATE_SOURCES
# # Exclude
# ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders
# ${CMAKE_CURRENT_SOURCE_DIR}/Platform)
#
function(CollectSourceFiles current_dir variable)
list(FIND ARGN "${current_dir}" IS_EXCLUDED)
if(IS_EXCLUDED EQUAL -1)
file(GLOB COLLECTED_SOURCES
${current_dir}/*.c
${current_dir}/*.cc
${current_dir}/*.cpp
${current_dir}/*.inl
${current_dir}/*.def
${current_dir}/*.h
${current_dir}/*.hh
${current_dir}/*.hpp)
list(APPEND ${variable} ${COLLECTED_SOURCES})
file(GLOB SUB_DIRECTORIES ${current_dir}/*)
foreach(SUB_DIRECTORY ${SUB_DIRECTORIES})
if (IS_DIRECTORY ${SUB_DIRECTORY})
CollectSourceFiles("${SUB_DIRECTORY}" "${variable}" "${ARGN}")
endif()
endforeach()
set(${variable} ${${variable}} PARENT_SCOPE)
endif()
endfunction()
# Collects all subdirectoroies into the given variable,
# which is useful to include all subdirectories.
# Ignores full qualified directories listed in the variadic arguments.
#
# Use it like:
# CollectIncludeDirectories(
# ${CMAKE_CURRENT_SOURCE_DIR}
# COMMON_PUBLIC_INCLUDES
# # Exclude
# ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders
# ${CMAKE_CURRENT_SOURCE_DIR}/Platform)
#
function(CollectIncludeDirectories current_dir variable)
list(FIND ARGN "${current_dir}" IS_EXCLUDED)
if(IS_EXCLUDED EQUAL -1)
list(APPEND ${variable} ${current_dir})
file(GLOB SUB_DIRECTORIES ${current_dir}/*)
foreach(SUB_DIRECTORY ${SUB_DIRECTORIES})
if (IS_DIRECTORY ${SUB_DIRECTORY})
CollectIncludeDirectories("${SUB_DIRECTORY}" "${variable}" "${ARGN}")
endif()
endforeach()
set(${variable} ${${variable}} PARENT_SCOPE)
endif()
endfunction()
+23
View File
@@ -0,0 +1,23 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Force out-of-source build
#
string(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}" BUILDING_IN_SOURCE)
if( BUILDING_IN_SOURCE )
message(FATAL_ERROR "
This project requires an out of source build. Remove the file 'CMakeCache.txt'
found in this directory before continuing, create a separate build directory
and run 'cmake path_to_project [options]' from there.
")
endif()
+14
View File
@@ -0,0 +1,14 @@
# check what platform we're on (64-bit or 32-bit), and create a simpler test than CMAKE_SIZEOF_VOID_P
if(CMAKE_SIZEOF_VOID_P MATCHES 8)
set(PLATFORM 64)
MESSAGE(STATUS "Detected 64-bit platform")
else()
set(PLATFORM 32)
MESSAGE(STATUS "Detected 32-bit platform")
endif()
if(WIN32)
include("${CMAKE_SOURCE_DIR}/cmake/platform/win/settings.cmake")
elseif(UNIX)
include("${CMAKE_SOURCE_DIR}/cmake/platform/unix/settings.cmake")
endif()
+67
View File
@@ -0,0 +1,67 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# An interface library to make the target com available to other targets
add_library(trinity-compile-option-interface INTERFACE)
# Use -std=c++11 instead of -std=gnu++11
set(CXX_EXTENSIONS OFF)
# An interface library to make the target features available to other targets
add_library(trinity-feature-interface INTERFACE)
target_compile_features(trinity-feature-interface
INTERFACE
cxx_std_20)
# An interface library to make the warnings level available to other targets
# This interface taget is set-up through the platform specific script
add_library(trinity-warning-interface INTERFACE)
# An interface used for all other interfaces
add_library(trinity-default-interface INTERFACE)
target_link_libraries(trinity-default-interface
INTERFACE
trinity-compile-option-interface
trinity-feature-interface)
# An interface used for silencing all warnings
add_library(trinity-no-warning-interface INTERFACE)
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
target_compile_options(trinity-no-warning-interface
INTERFACE
/W0)
else()
target_compile_options(trinity-no-warning-interface
INTERFACE
-w)
endif()
# An interface library to change the default behaviour
# to hide symbols automatically.
add_library(trinity-hidden-symbols-interface INTERFACE)
# An interface amalgamation which provides the flags and definitions
# used by the dependency targets.
add_library(trinity-dependency-interface INTERFACE)
target_link_libraries(trinity-dependency-interface
INTERFACE
trinity-default-interface
trinity-no-warning-interface
trinity-hidden-symbols-interface)
# An interface amalgamation which provides the flags and definitions
# used by the core targets.
add_library(trinity-core-interface INTERFACE)
target_link_libraries(trinity-core-interface
INTERFACE
trinity-default-interface
trinity-warning-interface)
+106
View File
@@ -0,0 +1,106 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# Returns the base path to the script directory in the source directory
function(WarnAboutSpacesInBuildPath)
# Only check win32 since unix doesn't allow spaces in paths
if (WIN32)
string(FIND "${CMAKE_BINARY_DIR}" " " SPACE_INDEX_POS)
if (SPACE_INDEX_POS GREATER -1)
message("")
message(WARNING " *** WARNING!\n"
" *** Your selected build directory contains spaces!\n"
" *** Please note that this will cause issues!")
endif()
endif()
endfunction()
# Returns the base path to the script directory in the source directory
function(GetScriptsBasePath variable)
set(${variable} "${CMAKE_SOURCE_DIR}/src/server/scripts" PARENT_SCOPE)
endfunction()
# Stores the absolut path of the given module in the variable
function(GetPathToScriptModule module variable)
GetScriptsBasePath(SCRIPTS_BASE_PATH)
set(${variable} "${SCRIPTS_BASE_PATH}/${module}" PARENT_SCOPE)
endfunction()
# Stores the project name of the given module in the variable
function(GetProjectNameOfScriptModule module variable)
string(TOLOWER "scripts_${SCRIPT_MODULE}" GENERATED_NAME)
set(${variable} "${GENERATED_NAME}" PARENT_SCOPE)
endfunction()
# Creates a list of all script modules
# and stores it in the given variable.
function(GetScriptModuleList variable)
GetScriptsBasePath(BASE_PATH)
file(GLOB LOCALE_SCRIPT_MODULE_LIST RELATIVE
${BASE_PATH}
${BASE_PATH}/*)
set(${variable})
foreach(SCRIPT_MODULE ${LOCALE_SCRIPT_MODULE_LIST})
GetPathToScriptModule(${SCRIPT_MODULE} SCRIPT_MODULE_PATH)
if (IS_DIRECTORY ${SCRIPT_MODULE_PATH})
list(APPEND ${variable} ${SCRIPT_MODULE})
endif()
endforeach()
set(${variable} ${${variable}} PARENT_SCOPE)
endfunction()
# Converts the given script module name into it's
# variable name which holds the linkage type.
function(ScriptModuleNameToVariable module variable)
string(TOUPPER ${module} ${variable})
set(${variable} "SCRIPTS_${${variable}}")
set(${variable} ${${variable}} PARENT_SCOPE)
endfunction()
# Stores in the given variable whether dynamic linking is required
function(IsDynamicLinkingRequired variable)
if(SCRIPTS MATCHES "dynamic")
set(IS_DEFAULT_VALUE_DYNAMIC ON)
endif()
GetScriptModuleList(SCRIPT_MODULE_LIST)
set(IS_REQUIRED OFF)
foreach(SCRIPT_MODULE ${SCRIPT_MODULE_LIST})
ScriptModuleNameToVariable(${SCRIPT_MODULE} SCRIPT_MODULE_VARIABLE)
if ((${SCRIPT_MODULE_VARIABLE} STREQUAL "dynamic") OR
(${SCRIPT_MODULE_VARIABLE} STREQUAL "default" AND IS_DEFAULT_VALUE_DYNAMIC))
set(IS_REQUIRED ON)
break()
endif()
endforeach()
set(${variable} ${IS_REQUIRED} PARENT_SCOPE)
endfunction()
# Stores the native variable name
function(GetNativeSharedLibraryName module variable)
if(WIN32)
set(${variable} "${module}.dll" PARENT_SCOPE)
elseif(APPLE)
set(${variable} "lib${module}.dylib" PARENT_SCOPE)
else()
set(${variable} "lib${module}.so" PARENT_SCOPE)
endif()
endfunction()
# Stores the native install path in the variable
function(GetInstallOffset variable)
if(WIN32)
set(${variable} "${CMAKE_INSTALL_PREFIX}/scripts" PARENT_SCOPE)
else()
set(${variable} "${CMAKE_INSTALL_PREFIX}/bin/scripts" PARENT_SCOPE)
endif()
endfunction()
+115
View File
@@ -0,0 +1,115 @@
# This file defines the following macros for developers to use in ensuring
# that installed software is of the right version:
#
# ENSURE_VERSION - test that a version number is greater than
# or equal to some minimum
# ENSURE_VERSION_RANGE - test that a version number is greater than
# or equal to some minimum and less than some
# maximum
# ENSURE_VERSION2 - deprecated, do not use in new code
#
# ENSURE_VERSION
# This macro compares version numbers of the form "x.y.z" or "x.y"
# ENSURE_VERSION( FOO_MIN_VERSION FOO_VERSION_FOUND FOO_VERSION_OK)
# will set FOO_VERSION_OK to true if FOO_VERSION_FOUND >= FOO_MIN_VERSION
# Leading and trailing text is ok, e.g.
# ENSURE_VERSION( "2.5.31" "flex 2.5.4a" VERSION_OK)
# which means 2.5.31 is required and "flex 2.5.4a" is what was found on the system
# Copyright (c) 2006, David Faure, <faure@kde.org>
# Copyright (c) 2007, Will Stephenson <wstephenson@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
# ENSURE_VERSION_RANGE
# This macro ensures that a version number of the form
# "x.y.z" or "x.y" falls within a range defined by
# min_version <= found_version < max_version.
# If this expression holds, FOO_VERSION_OK will be set TRUE
#
# Example: ENSURE_VERSION_RANGE3( "0.1.0" ${FOOCODE_VERSION} "0.7.0" FOO_VERSION_OK )
#
# This macro will break silently if any of x,y,z are greater than 100.
#
# Copyright (c) 2007, Will Stephenson <wstephenson@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
# NORMALIZE_VERSION
# Helper macro to convert version numbers of the form "x.y.z"
# to an integer equal to 10^4 * x + 10^2 * y + z
#
# This macro will break silently if any of x,y,z are greater than 100.
#
# Copyright (c) 2006, David Faure, <faure@kde.org>
# Copyright (c) 2007, Will Stephenson <wstephenson@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
# CHECK_RANGE_INCLUSIVE_LOWER
# Helper macro to check whether x <= y < z
#
# Copyright (c) 2007, Will Stephenson <wstephenson@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
MACRO(NORMALIZE_VERSION _requested_version _normalized_version)
STRING(REGEX MATCH "[^0-9]*[0-9]+\\.[0-9]+\\.[0-9]+.*" _threePartMatch "${_requested_version}")
if (_threePartMatch)
# parse the parts of the version string
STRING(REGEX REPLACE "[^0-9]*([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" _major_vers "${_requested_version}")
STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.([0-9]+)\\.[0-9]+.*" "\\1" _minor_vers "${_requested_version}")
STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" _patch_vers "${_requested_version}")
else (_threePartMatch)
STRING(REGEX REPLACE "([0-9]+)\\.[0-9]+" "\\1" _major_vers "${_requested_version}")
STRING(REGEX REPLACE "[0-9]+\\.([0-9]+)" "\\1" _minor_vers "${_requested_version}")
set(_patch_vers "0")
endif (_threePartMatch)
# compute an overall version number which can be compared at once
MATH(EXPR ${_normalized_version} "${_major_vers}*10000 + ${_minor_vers}*100 + ${_patch_vers}")
ENDMACRO(NORMALIZE_VERSION)
MACRO(CHECK_RANGE_INCLUSIVE_LOWER _lower_limit _value _upper_limit _ok)
if (${_value} LESS ${_lower_limit})
set( ${_ok} FALSE )
elseif (${_value} EQUAL ${_lower_limit})
set( ${_ok} TRUE )
elseif (${_value} EQUAL ${_upper_limit})
set( ${_ok} FALSE )
elseif (${_value} GREATER ${_upper_limit})
set( ${_ok} FALSE )
else (${_value} LESS ${_lower_limit})
set( ${_ok} TRUE )
endif (${_value} LESS ${_lower_limit})
ENDMACRO(CHECK_RANGE_INCLUSIVE_LOWER)
MACRO(ENSURE_VERSION requested_version found_version var_too_old)
NORMALIZE_VERSION( ${requested_version} req_vers_num )
NORMALIZE_VERSION( ${found_version} found_vers_num )
if (found_vers_num LESS req_vers_num)
set( ${var_too_old} FALSE )
else (found_vers_num LESS req_vers_num)
set( ${var_too_old} TRUE )
endif (found_vers_num LESS req_vers_num)
ENDMACRO(ENSURE_VERSION)
MACRO(ENSURE_VERSION2 requested_version2 found_version2 var_too_old2)
ENSURE_VERSION( ${requested_version2} ${found_version2} ${var_too_old2})
ENDMACRO(ENSURE_VERSION2)
MACRO(ENSURE_VERSION_RANGE min_version found_version max_version var_ok)
NORMALIZE_VERSION( ${min_version} req_vers_num )
NORMALIZE_VERSION( ${found_version} found_vers_num )
NORMALIZE_VERSION( ${max_version} max_vers_num )
CHECK_RANGE_INCLUSIVE_LOWER( ${req_vers_num} ${found_vers_num} ${max_vers_num} ${var_ok})
ENDMACRO(ENSURE_VERSION_RANGE)
+325
View File
@@ -0,0 +1,325 @@
# This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#[=======================================================================[.rst:
FindMySQL
-----------
Find MySQL.
Imported Targets
^^^^^^^^^^^^^^^^
This module defines the following :prop_tgt:`IMPORTED` targets:
``MySQL::MySQL``
MySQL client library, if found.
Result Variables
^^^^^^^^^^^^^^^^
This module will set the following variables in your project:
``MYSQL_FOUND``
System has MySQL.
``MYSQL_INCLUDE_DIR``
MySQL include directory.
``MYSQL_LIBRARY``
MySQL library.
``MYSQL_EXECUTABLE``
Path to mysql client binary.
Hints
^^^^^
Set ``MYSQL_ROOT_DIR`` to the root directory of MySQL installation.
#]=======================================================================]
set(MYSQL_FOUND 0)
set(_MYSQL_ROOT_HINTS
${MYSQL_ROOT_DIR}
ENV MYSQL_ROOT_DIR
)
if(UNIX)
set(MYSQL_CONFIG_PREFER_PATH "$ENV{MYSQL_HOME}/bin" CACHE FILEPATH
"preferred path to MySQL (mysql_config)"
)
find_program(MYSQL_CONFIG mysql_config
${MYSQL_CONFIG_PREFER_PATH}
/usr/local/mysql/bin/
/usr/local/bin/
/usr/bin/
)
if(MYSQL_CONFIG)
message(STATUS "Using mysql-config: ${MYSQL_CONFIG}")
# set INCLUDE_DIR
execute_process(
COMMAND "${MYSQL_CONFIG}" --include
OUTPUT_VARIABLE MY_TMP
OUTPUT_STRIP_TRAILING_WHITESPACE
)
string(REGEX REPLACE "-I([^ ]*)( .*)?" "\\1" MY_TMP "${MY_TMP}")
set(MYSQL_ADD_INCLUDE_PATH ${MY_TMP} CACHE FILEPATH INTERNAL)
#message("[DEBUG] MYSQL ADD_INCLUDE_PATH : ${MYSQL_ADD_INCLUDE_PATH}")
# set LIBRARY_DIR
execute_process(
COMMAND "${MYSQL_CONFIG}" --libs_r
OUTPUT_VARIABLE MY_TMP
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(MYSQL_ADD_LIBRARIES "")
string(REGEX MATCHALL "-l[^ ]*" MYSQL_LIB_LIST "${MY_TMP}")
foreach(LIB ${MYSQL_LIB_LIST})
string(REGEX REPLACE "[ ]*-l([^ ]*)" "\\1" LIB "${LIB}")
list(APPEND MYSQL_ADD_LIBRARIES "${LIB}")
#message("[DEBUG] MYSQL ADD_LIBRARIES : ${MYSQL_ADD_LIBRARIES}")
endforeach(LIB ${MYSQL_LIB_LIST})
set(MYSQL_ADD_LIBRARIES_PATH "")
string(REGEX MATCHALL "-L[^ ]*" MYSQL_LIBDIR_LIST "${MY_TMP}")
foreach(LIB ${MYSQL_LIBDIR_LIST})
string(REGEX REPLACE "[ ]*-L([^ ]*)" "\\1" LIB "${LIB}")
list(APPEND MYSQL_ADD_LIBRARIES_PATH "${LIB}")
#message("[DEBUG] MYSQL ADD_LIBRARIES_PATH : ${MYSQL_ADD_LIBRARIES_PATH}")
endforeach(LIB ${MYSQL_LIBS})
else(MYSQL_CONFIG)
set(MYSQL_ADD_LIBRARIES "")
list(APPEND MYSQL_ADD_LIBRARIES "mysqlclient_r")
endif(MYSQL_CONFIG)
endif(UNIX)
set(_MYSQL_ROOT_PATHS)
if(WIN32)
# read environment variables and change \ to /
file(TO_CMAKE_PATH "$ENV{PROGRAMFILES}" PROGRAM_FILES_32)
file(TO_CMAKE_PATH "$ENV{ProgramW6432}" PROGRAM_FILES_64)
cmake_host_system_information(
RESULT
_MYSQL_ROOT_HINTS_SUBKEYS
QUERY
WINDOWS_REGISTRY
"HKEY_LOCAL_MACHINE\\SOFTWARE\\MySQL AB" SUBKEYS
VIEW BOTH
)
list(SORT _MYSQL_ROOT_HINTS_SUBKEYS COMPARE NATURAL ORDER DESCENDING)
set(_MYSQL_ROOT_HINTS_REGISTRY_LOCATIONS)
foreach(subkey IN LISTS _MYSQL_ROOT_HINTS_SUBKEYS)
cmake_host_system_information(
RESULT
_MYSQL_ROOT_HINTS_REGISTRY_LOCATION
QUERY
WINDOWS_REGISTRY
"HKEY_LOCAL_MACHINE\\SOFTWARE\\MySQL AB\\${subkey}" VALUE "Location"
VIEW BOTH
)
list(APPEND _MYSQL_ROOT_HINTS_REGISTRY_LOCATIONS ${_MYSQL_ROOT_HINTS_REGISTRY_LOCATION})
endforeach()
set(_MYSQL_ROOT_HINTS
${_MYSQL_ROOT_HINTS}
${_MYSQL_ROOT_HINTS_REGISTRY_LOCATIONS}
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\MariaDB 10.4;INSTALLDIR]"
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\MariaDB 10.4 (x64);INSTALLDIR]"
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\MariaDB 10.5;INSTALLDIR]"
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\MariaDB 10.5 (x64);INSTALLDIR]"
)
file(GLOB _MYSQL_ROOT_PATHS_VERSION_SUBDIRECTORIES
LIST_DIRECTORIES TRUE
"${PROGRAM_FILES_64}/MySQL/MySQL Server *"
"${PROGRAM_FILES_32}/MySQL/MySQL Server *"
"$ENV{SystemDrive}/MySQL/MySQL Server *"
)
list(SORT _MYSQL_ROOT_PATHS_VERSION_SUBDIRECTORIES COMPARE NATURAL ORDER DESCENDING)
set(_MYSQL_ROOT_PATHS
${_MYSQL_ROOT_PATHS}
${_MYSQL_ROOT_PATHS_VERSION_SUBDIRECTORIES}
"${PROGRAM_FILES_64}/MySQL"
"${PROGRAM_FILES_32}/MySQL"
"$ENV{SystemDrive}/MySQL"
)
endif(WIN32)
find_path(MYSQL_INCLUDE_DIR
NAMES
mysql.h
HINTS
${_MYSQL_ROOT_HINTS}
PATHS
${MYSQL_ADD_INCLUDE_PATH}
/usr/include
/usr/include/mysql
/usr/local/include
/usr/local/include/mysql
/usr/local/mysql/include
${_MYSQL_ROOT_PATHS}
PATH_SUFFIXES
include
include/mysql
DOC
"Specify the directory containing mysql.h."
)
if(UNIX)
foreach(LIB ${MYSQL_ADD_LIBRARIES})
find_library(MYSQL_LIBRARY
NAMES
mysql libmysql ${LIB}
PATHS
${MYSQL_ADD_LIBRARIES_PATH}
/usr/lib
/usr/lib/mysql
/usr/local/lib
/usr/local/lib/mysql
/usr/local/mysql/lib
DOC "Specify the location of the mysql library here."
)
endforeach(LIB ${MYSQL_ADD_LIBRARY})
endif(UNIX)
if(WIN32)
find_library(MYSQL_LIBRARY
NAMES
libmysql libmariadb
HINTS
${_MYSQL_ROOT_HINTS}
PATHS
${MYSQL_ADD_LIBRARIES_PATH}
${_MYSQL_ROOT_PATHS}
PATH_SUFFIXES
lib
lib/opt
DOC "Specify the location of the mysql library here."
)
endif(WIN32)
# On Windows you typically don't need to include any extra libraries
# to build MYSQL stuff.
if(NOT WIN32)
find_library(MYSQL_EXTRA_LIBRARIES
NAMES
z zlib
PATHS
/usr/lib
/usr/local/lib
DOC
"if more libraries are necessary to link in a MySQL client (typically zlib), specify them here."
)
else(NOT WIN32)
set(MYSQL_EXTRA_LIBRARIES "")
endif(NOT WIN32)
if(UNIX)
find_program(MYSQL_EXECUTABLE mysql
PATHS
${MYSQL_CONFIG_PREFER_PATH}
/usr/local/mysql/bin/
/usr/local/bin/
/usr/bin/
DOC
"path to your mysql binary."
)
endif(UNIX)
if(WIN32)
find_program(MYSQL_EXECUTABLE mysql
HINTS
${_MYSQL_ROOT_HINTS}
PATHS
${_MYSQL_ROOT_PATHS}
PATH_SUFFIXES
bin
bin/opt
DOC
"path to your mysql binary."
)
endif(WIN32)
unset(MySQL_lib_WANTED)
unset(MySQL_binary_WANTED)
set(MYSQL_REQUIRED_VARS "")
foreach(_comp IN LISTS MySQL_FIND_COMPONENTS)
if(_comp STREQUAL "lib")
set(MySQL_${_comp}_WANTED TRUE)
if(MySQL_FIND_REQUIRED_${_comp})
list(APPEND MYSQL_REQUIRED_VARS "MYSQL_LIBRARY")
list(APPEND MYSQL_REQUIRED_VARS "MYSQL_INCLUDE_DIR")
endif()
if(EXISTS "${MYSQL_LIBRARY}" AND EXISTS "${MYSQL_INCLUDE_DIR}")
set(MySQL_${_comp}_FOUND TRUE)
else()
set(MySQL_${_comp}_FOUND FALSE)
endif()
elseif(_comp STREQUAL "binary")
set(MySQL_${_comp}_WANTED TRUE)
if(MySQL_FIND_REQUIRED_${_comp})
list(APPEND MYSQL_REQUIRED_VARS "MYSQL_EXECUTABLE")
endif()
if(EXISTS "${MYSQL_EXECUTABLE}" )
set(MySQL_${_comp}_FOUND TRUE)
else()
set(MySQL_${_comp}_FOUND FALSE)
endif()
else()
message(WARNING "${_comp} is not a valid MySQL component")
set(MySQL_${_comp}_FOUND FALSE)
endif()
endforeach()
unset(_comp)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MySQL
REQUIRED_VARS
${MYSQL_REQUIRED_VARS}
HANDLE_COMPONENTS
FAIL_MESSAGE
"Could not find the MySQL libraries! Please install the development libraries and headers"
)
unset(MYSQL_REQUIRED_VARS)
if(MYSQL_FOUND)
if(MySQL_lib_WANTED AND MySQL_lib_FOUND)
message(STATUS "Found MySQL library: ${MYSQL_LIBRARY}")
message(STATUS "Found MySQL headers: ${MYSQL_INCLUDE_DIR}")
endif()
if(MySQL_binary_WANTED AND MySQL_binary_FOUND)
message(STATUS "Found MySQL executable: ${MYSQL_EXECUTABLE}")
endif()
mark_as_advanced(MYSQL_FOUND MYSQL_LIBRARY MYSQL_EXTRA_LIBRARIES MYSQL_INCLUDE_DIR MYSQL_EXECUTABLE)
if(NOT TARGET MySQL::MySQL AND MySQL_lib_WANTED AND MySQL_lib_FOUND)
add_library(MySQL::MySQL UNKNOWN IMPORTED)
set_target_properties(MySQL::MySQL
PROPERTIES
IMPORTED_LOCATION
"${MYSQL_LIBRARY}"
INTERFACE_INCLUDE_DIRECTORIES
"${MYSQL_INCLUDE_DIR}")
endif()
else()
message(FATAL_ERROR "Could not find the MySQL libraries! Please install the development libraries and headers")
endif()
+821
View File
@@ -0,0 +1,821 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindOpenSSL
-----------
Find the OpenSSL encryption library.
This module finds an installed OpenSSL library and determines its version.
.. versionadded:: 3.19
When a version is requested, it can be specified as a simple value or as a
range. For a detailed description of version range usage and capabilities,
refer to the :command:`find_package` command.
.. versionadded:: 3.18
Support for OpenSSL 3.0.
Optional COMPONENTS
^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.12
This module supports two optional COMPONENTS: ``Crypto`` and ``SSL``. Both
components have associated imported targets, as described below.
Imported Targets
^^^^^^^^^^^^^^^^
.. versionadded:: 3.4
This module defines the following :prop_tgt:`IMPORTED` targets:
``OpenSSL::SSL``
The OpenSSL ``ssl`` library, if found.
``OpenSSL::Crypto``
The OpenSSL ``crypto`` library, if found.
``OpenSSL::applink``
.. versionadded:: 3.18
The OpenSSL ``applink`` components that might be need to be compiled into
projects under MSVC. This target is available only if found OpenSSL version
is not less than 0.9.8. By linking this target the above OpenSSL targets can
be linked even if the project has different MSVC runtime configurations with
the above OpenSSL targets. This target has no effect on platforms other than
MSVC.
NOTE: Due to how ``INTERFACE_SOURCES`` are consumed by the consuming target,
unless you certainly know what you are doing, it is always preferred to link
``OpenSSL::applink`` target as ``PRIVATE`` and to make sure that this target is
linked at most once for the whole dependency graph of any library or
executable:
.. code-block:: cmake
target_link_libraries(myTarget PRIVATE OpenSSL::applink)
Otherwise you would probably encounter unexpected random problems when building
and linking, as both the ISO C and the ISO C++ standard claims almost nothing
about what a link process should be.
Result Variables
^^^^^^^^^^^^^^^^
This module will set the following variables in your project:
``OPENSSL_FOUND``
System has the OpenSSL library. If no components are requested it only
requires the crypto library.
``OPENSSL_INCLUDE_DIR``
The OpenSSL include directory.
``OPENSSL_CRYPTO_LIBRARY``
The OpenSSL crypto library.
``OPENSSL_CRYPTO_LIBRARIES``
The OpenSSL crypto library and its dependencies.
``OPENSSL_SSL_LIBRARY``
The OpenSSL SSL library.
``OPENSSL_SSL_LIBRARIES``
The OpenSSL SSL library and its dependencies.
``OPENSSL_LIBRARIES``
All OpenSSL libraries and their dependencies.
``OPENSSL_VERSION``
This is set to ``$major.$minor.$revision$patch`` (e.g. ``0.9.8s``).
``OPENSSL_APPLINK_SOURCE``
The sources in the target ``OpenSSL::applink`` that is mentioned above. This
variable shall always be undefined if found openssl version is less than
0.9.8 or if platform is not MSVC.
Hints
^^^^^
The following variables may be set to control search behavior:
``OPENSSL_ROOT_DIR``
Set to the root directory of an OpenSSL installation.
``OPENSSL_USE_STATIC_LIBS``
.. versionadded:: 3.4
Set to ``TRUE`` to look for static libraries.
``OPENSSL_MSVC_STATIC_RT``
.. versionadded:: 3.5
Set to ``TRUE`` to choose the MT version of the lib.
``ENV{PKG_CONFIG_PATH}``
On UNIX-like systems, ``pkg-config`` is used to locate the system OpenSSL.
Set the ``PKG_CONFIG_PATH`` environment variable to look in alternate
locations. Useful on multi-lib systems.
#]=======================================================================]
macro(_OpenSSL_test_and_find_dependencies ssl_library crypto_library)
unset(_OpenSSL_extra_static_deps)
if(UNIX AND
(("${ssl_library}" MATCHES "\\${CMAKE_STATIC_LIBRARY_SUFFIX}$") OR
("${crypto_library}" MATCHES "\\${CMAKE_STATIC_LIBRARY_SUFFIX}$")))
set(_OpenSSL_has_dependencies TRUE)
unset(_OpenSSL_has_dependency_zlib)
if(OPENSSL_USE_STATIC_LIBS)
set(_OpenSSL_libs "${_OPENSSL_STATIC_LIBRARIES}")
set(_OpenSSL_ldflags_other "${_OPENSSL_STATIC_LDFLAGS_OTHER}")
else()
set(_OpenSSL_libs "${_OPENSSL_LIBRARIES}")
set(_OpenSSL_ldflags_other "${_OPENSSL_LDFLAGS_OTHER}")
endif()
if(_OpenSSL_libs)
unset(_OpenSSL_has_dependency_dl)
foreach(_OPENSSL_DEP_LIB IN LISTS _OpenSSL_libs)
if (_OPENSSL_DEP_LIB STREQUAL "ssl" OR _OPENSSL_DEP_LIB STREQUAL "crypto")
# ignoring: these are the targets
elseif(_OPENSSL_DEP_LIB STREQUAL CMAKE_DL_LIBS)
set(_OpenSSL_has_dependency_dl TRUE)
elseif(_OPENSSL_DEP_LIB STREQUAL "z")
find_package(ZLIB)
set(_OpenSSL_has_dependency_zlib TRUE)
else()
list(APPEND _OpenSSL_extra_static_deps "${_OPENSSL_DEP_LIB}")
endif()
endforeach()
unset(_OPENSSL_DEP_LIB)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(_OpenSSL_has_dependency_dl TRUE)
endif()
if(_OpenSSL_ldflags_other)
unset(_OpenSSL_has_dependency_threads)
foreach(_OPENSSL_DEP_LDFLAG IN LISTS _OpenSSL_ldflags_other)
if (_OPENSSL_DEP_LDFLAG STREQUAL "-pthread")
set(_OpenSSL_has_dependency_threads TRUE)
find_package(Threads)
endif()
endforeach()
unset(_OPENSSL_DEP_LDFLAG)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(_OpenSSL_has_dependency_threads TRUE)
find_package(Threads)
endif()
unset(_OpenSSL_libs)
unset(_OpenSSL_ldflags_other)
else()
set(_OpenSSL_has_dependencies FALSE)
endif()
endmacro()
function(_OpenSSL_add_dependencies libraries_var)
if(_OpenSSL_has_dependency_zlib)
list(APPEND ${libraries_var} ${ZLIB_LIBRARY})
endif()
if(_OpenSSL_has_dependency_threads)
list(APPEND ${libraries_var} ${CMAKE_THREAD_LIBS_INIT})
endif()
if(_OpenSSL_has_dependency_dl)
list(APPEND ${libraries_var} ${CMAKE_DL_LIBS})
endif()
list(APPEND ${libraries_var} ${_OpenSSL_extra_static_deps})
set(${libraries_var} ${${libraries_var}} PARENT_SCOPE)
endfunction()
function(_OpenSSL_target_add_dependencies target)
if(_OpenSSL_has_dependencies)
if(_OpenSSL_has_dependency_zlib)
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ZLIB::ZLIB )
endif()
if(_OpenSSL_has_dependency_threads)
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES Threads::Threads)
endif()
if(_OpenSSL_has_dependency_dl)
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${CMAKE_DL_LIBS} )
endif()
if(_OpenSSL_extra_static_deps)
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${_OpenSSL_extra_static_deps})
endif()
endif()
if(WIN32 AND OPENSSL_USE_STATIC_LIBS)
if(WINCE)
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ws2 )
else()
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES ws2_32 )
endif()
set_property( TARGET ${target} APPEND PROPERTY INTERFACE_LINK_LIBRARIES crypt32 )
endif()
endfunction()
if (UNIX)
find_package(PkgConfig QUIET)
pkg_check_modules(_OPENSSL QUIET openssl)
endif ()
# Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES
if(OPENSSL_USE_STATIC_LIBS)
set(_openssl_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
if(MSVC)
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
else()
set(CMAKE_FIND_LIBRARY_SUFFIXES .a )
endif()
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "QNX" AND
CMAKE_SYSTEM_VERSION VERSION_GREATER_EQUAL "7.0" AND CMAKE_SYSTEM_VERSION VERSION_LESS "7.1" AND
OpenSSL_FIND_VERSION VERSION_GREATER_EQUAL "1.1" AND OpenSSL_FIND_VERSION VERSION_LESS "1.2")
# QNX 7.0.x provides openssl 1.0.2 and 1.1.1 in parallel:
# * openssl 1.0.2: libcrypto.so.2 and libssl.so.2, headers under usr/include/openssl
# * openssl 1.1.1: libcrypto1_1.so.2.1 and libssl1_1.so.2.1, header under usr/include/openssl1_1
# See http://www.qnx.com/developers/articles/rel_6726_0.html
set(_OPENSSL_FIND_PATH_SUFFIX "openssl1_1")
set(_OPENSSL_NAME_POSTFIX "1_1")
else()
set(_OPENSSL_FIND_PATH_SUFFIX "include")
endif()
if (OPENSSL_ROOT_DIR OR NOT "$ENV{OPENSSL_ROOT_DIR}" STREQUAL "")
set(_OPENSSL_ROOT_HINTS HINTS ${OPENSSL_ROOT_DIR} ENV OPENSSL_ROOT_DIR)
set(_OPENSSL_ROOT_PATHS NO_DEFAULT_PATH)
elseif (MSVC)
# http://www.slproweb.com/products/Win32OpenSSL.html
set(_OPENSSL_MSI_INSTALL_GUIDS "")
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
if(TRINITY_SYSTEM_PROCESSOR STREQUAL "arm64")
set(_arch "Win64-ARM")
set(_OPENSSL_MSI_INSTALL_GUIDS "99C28AFA-6419-40B1-B88D-32B810BB4234")
else()
set(_arch "Win64")
set(_OPENSSL_MSI_INSTALL_GUIDS "117551DB-A110-4BBD-BB05-CFE0BCB3ED31" "50A9FBE2-0F8C-4D5D-97A4-A63A71C4EA1E")
endif()
file(TO_CMAKE_PATH "$ENV{PROGRAMFILES}" _programfiles)
set(_OPENSSL_ROOT_HINTS HINTS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OpenSSL (64-bit)_is1;Inno Setup: App Path]")
else()
set(_arch "Win32")
set(_progfiles_x86 "ProgramFiles(x86)")
if(NOT "$ENV{${_progfiles_x86}}" STREQUAL "")
# under windows 64 bit machine
file(TO_CMAKE_PATH "$ENV{${_progfiles_x86}}" _programfiles)
else()
# under windows 32 bit machine
file(TO_CMAKE_PATH "$ENV{ProgramFiles}" _programfiles)
endif()
set(_OPENSSL_ROOT_HINTS HINTS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OpenSSL (32-bit)_is1;Inno Setup: App Path]")
set(_OPENSSL_MSI_INSTALL_GUIDS "A1EEC576-43B9-4E75-9E02-03DA542D2A38" "31D2408A-9CAE-4988-9EC3-F40FDE7D6AE5")
endif()
# If OpenSSL was installed using .msi package instead of .exe, Inno Setup registry values are not written to Uninstall\OpenSSL
# but because it is only a shim around Inno Setup it does write the location of uninstaller which we can use to determine path
foreach(_OPENSSL_MSI_INSTALL_GUID IN LISTS _OPENSSL_MSI_INSTALL_GUIDS)
get_filename_component(_OPENSSL_MSI_INSTALL_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Inno Setup MSIs\\${_OPENSSL_MSI_INSTALL_GUID};]" DIRECTORY)
if(NOT _OPENSSL_MSI_INSTALL_PATH STREQUAL "/")
list(INSERT _OPENSSL_ROOT_HINTS 2 ${_OPENSSL_MSI_INSTALL_PATH})
endif()
endforeach()
unset(_OPENSSL_MSI_INSTALL_GUIDS)
set(_OPENSSL_ROOT_PATHS
PATHS
"${_programfiles}/OpenSSL"
"${_programfiles}/OpenSSL-${_arch}"
"C:/OpenSSL/"
"C:/OpenSSL-${_arch}/"
)
unset(_programfiles)
unset(_arch)
endif ()
if(HOMEBREW_PREFIX)
list(APPEND _OPENSSL_ROOT_HINTS
"${HOMEBREW_PREFIX}/opt/openssl@3")
endif()
set(_OPENSSL_ROOT_HINTS_AND_PATHS
${_OPENSSL_ROOT_HINTS}
${_OPENSSL_ROOT_PATHS}
)
find_path(OPENSSL_INCLUDE_DIR
NAMES
openssl/ssl.h
${_OPENSSL_ROOT_HINTS_AND_PATHS}
HINTS
${_OPENSSL_INCLUDEDIR}
${_OPENSSL_INCLUDE_DIRS}
PATH_SUFFIXES
${_OPENSSL_FIND_PATH_SUFFIX}
)
if(WIN32 AND NOT CYGWIN)
if(MSVC)
# /MD and /MDd are the standard values - if someone wants to use
# others, the libnames have to change here too
# use also ssl and ssleay32 in debug as fallback for openssl < 0.9.8b
# enable OPENSSL_MSVC_STATIC_RT to get the libs build /MT (Multithreaded no-DLL)
# In Visual C++ naming convention each of these four kinds of Windows libraries has it's standard suffix:
# * MD for dynamic-release
# * MDd for dynamic-debug
# * MT for static-release
# * MTd for static-debug
# Implementation details:
# We are using the libraries located in the VC subdir instead of the parent directory even though :
# libeay32MD.lib is identical to ../libeay32.lib, and
# ssleay32MD.lib is identical to ../ssleay32.lib
# enable OPENSSL_USE_STATIC_LIBS to use the static libs located in lib/VC/static
if (OPENSSL_MSVC_STATIC_RT)
set(_OPENSSL_MSVC_RT_MODE "MT")
else ()
set(_OPENSSL_MSVC_RT_MODE "MD")
endif ()
# Since OpenSSL 1.1, lib names are like libcrypto32MTd.lib and libssl32MTd.lib
if( "${CMAKE_SIZEOF_VOID_P}" STREQUAL "8" )
set(_OPENSSL_MSVC_ARCH_SUFFIX "64")
if(TRINITY_SYSTEM_PROCESSOR STREQUAL "arm64")
set(_OPENSSL_MSVC_ARCH_DIRECTORY "arm64")
else()
set(_OPENSSL_MSVC_ARCH_DIRECTORY "x64")
endif()
else()
set(_OPENSSL_MSVC_ARCH_SUFFIX "32")
set(_OPENSSL_MSVC_ARCH_DIRECTORY "x86")
endif()
if(OPENSSL_USE_STATIC_LIBS)
set(_OPENSSL_STATIC_SUFFIX
"_static"
)
set(_OPENSSL_PATH_SUFFIXES
"lib/VC/static"
"VC/static"
"lib"
)
else()
set(_OPENSSL_STATIC_SUFFIX
""
)
set(_OPENSSL_PATH_SUFFIXES
"lib/VC"
"VC"
"lib"
)
endif ()
find_library(LIB_EAY_DEBUG
NAMES
libcrypto${_OPENSSL_STATIC_SUFFIX}
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
"lib/VC/${_OPENSSL_MSVC_ARCH_DIRECTORY}/${_OPENSSL_MSVC_RT_MODE}d"
)
if(NOT LIB_EAY_DEBUG)
find_library(LIB_EAY_DEBUG
NAMES
# When OpenSSL is built with default options, the static library name is suffixed with "_static".
# Looking the "libcrypto_static.lib" with a higher priority than "libcrypto.lib" which is the
# import library of "libcrypto.dll".
libcrypto${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libcrypto${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libcrypto${_OPENSSL_STATIC_SUFFIX}d
libeay32${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libeay32${_OPENSSL_STATIC_SUFFIX}d
crypto${_OPENSSL_STATIC_SUFFIX}d
# When OpenSSL is built with the "-static" option, only the static build is produced,
# and it is not suffixed with "_static".
libcrypto${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libcrypto${_OPENSSL_MSVC_RT_MODE}d
libcryptod
libeay32${_OPENSSL_MSVC_RT_MODE}d
libeay32d
cryptod
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
${_OPENSSL_PATH_SUFFIXES}
)
endif()
find_library(LIB_EAY_RELEASE
NAMES
# When OpenSSL is built with default options, the static library name is suffixed with "_static".
# Looking the "libcrypto_static.lib" with a higher priority than "libcrypto.lib" which is the
# import library of "libcrypto.dll".
libcrypto${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libcrypto${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libcrypto${_OPENSSL_STATIC_SUFFIX}
libeay32${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libeay32${_OPENSSL_STATIC_SUFFIX}
crypto${_OPENSSL_STATIC_SUFFIX}
# When OpenSSL is built with the "-static" option, only the static build is produced,
# and it is not suffixed with "_static".
libcrypto${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libcrypto${_OPENSSL_MSVC_RT_MODE}
libcrypto
libeay32${_OPENSSL_MSVC_RT_MODE}
libeay32
crypto
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
${_OPENSSL_PATH_SUFFIXES}
"lib/VC/${_OPENSSL_MSVC_ARCH_DIRECTORY}/${_OPENSSL_MSVC_RT_MODE}"
)
find_library(SSL_EAY_DEBUG
NAMES
libssl${_OPENSSL_STATIC_SUFFIX}
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
"lib/VC/${_OPENSSL_MSVC_ARCH_DIRECTORY}/${_OPENSSL_MSVC_RT_MODE}d"
)
if(NOT SSL_EAY_DEBUG)
find_library(SSL_EAY_DEBUG
NAMES
# When OpenSSL is built with default options, the static library name is suffixed with "_static".
# Looking the "libssl_static.lib" with a higher priority than "libssl.lib" which is the
# import library of "libssl.dll".
libssl${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libssl${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libssl${_OPENSSL_STATIC_SUFFIX}d
ssleay32${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
ssleay32${_OPENSSL_STATIC_SUFFIX}d
ssl${_OPENSSL_STATIC_SUFFIX}d
# When OpenSSL is built with the "-static" option, only the static build is produced,
# and it is not suffixed with "_static".
libssl${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}d
libssl${_OPENSSL_MSVC_RT_MODE}d
libssld
ssleay32${_OPENSSL_MSVC_RT_MODE}d
ssleay32d
ssld
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
${_OPENSSL_PATH_SUFFIXES}
)
endif()
find_library(SSL_EAY_RELEASE
NAMES
# When OpenSSL is built with default options, the static library name is suffixed with "_static".
# Looking the "libssl_static.lib" with a higher priority than "libssl.lib" which is the
# import library of "libssl.dll".
libssl${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libssl${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libssl${_OPENSSL_STATIC_SUFFIX}
ssleay32${_OPENSSL_STATIC_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
ssleay32${_OPENSSL_STATIC_SUFFIX}
ssl${_OPENSSL_STATIC_SUFFIX}
# When OpenSSL is built with the "-static" option, only the static build is produced,
# and it is not suffixed with "_static".
libssl${_OPENSSL_MSVC_ARCH_SUFFIX}${_OPENSSL_MSVC_RT_MODE}
libssl${_OPENSSL_MSVC_RT_MODE}
libssl
ssleay32${_OPENSSL_MSVC_RT_MODE}
ssleay32
ssl
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
${_OPENSSL_PATH_SUFFIXES}
"lib/VC/${_OPENSSL_MSVC_ARCH_DIRECTORY}/${_OPENSSL_MSVC_RT_MODE}"
)
set(LIB_EAY_LIBRARY_DEBUG "${LIB_EAY_DEBUG}")
set(LIB_EAY_LIBRARY_RELEASE "${LIB_EAY_RELEASE}")
set(SSL_EAY_LIBRARY_DEBUG "${SSL_EAY_DEBUG}")
set(SSL_EAY_LIBRARY_RELEASE "${SSL_EAY_RELEASE}")
include(SelectLibraryConfigurations)
select_library_configurations(LIB_EAY)
select_library_configurations(SSL_EAY)
mark_as_advanced(LIB_EAY_LIBRARY_DEBUG LIB_EAY_LIBRARY_RELEASE
SSL_EAY_LIBRARY_DEBUG SSL_EAY_LIBRARY_RELEASE)
set(OPENSSL_SSL_LIBRARY ${SSL_EAY_LIBRARY} )
set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY_LIBRARY} )
elseif(MINGW)
# same player, for MinGW
set(LIB_EAY_NAMES crypto libeay32)
set(SSL_EAY_NAMES ssl ssleay32)
find_library(LIB_EAY
NAMES
${LIB_EAY_NAMES}
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
"lib/MinGW"
"lib"
"lib64"
)
find_library(SSL_EAY
NAMES
${SSL_EAY_NAMES}
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
"lib/MinGW"
"lib"
"lib64"
)
mark_as_advanced(SSL_EAY LIB_EAY)
set(OPENSSL_SSL_LIBRARY ${SSL_EAY} )
set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY} )
unset(LIB_EAY_NAMES)
unset(SSL_EAY_NAMES)
else()
# Not sure what to pick for -say- intel, let's use the toplevel ones and hope someone report issues:
find_library(LIB_EAY
NAMES
libcrypto
libeay32
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
HINTS
${_OPENSSL_LIBDIR}
PATH_SUFFIXES
lib
)
find_library(SSL_EAY
NAMES
libssl
ssleay32
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
HINTS
${_OPENSSL_LIBDIR}
PATH_SUFFIXES
lib
)
mark_as_advanced(SSL_EAY LIB_EAY)
set(OPENSSL_SSL_LIBRARY ${SSL_EAY} )
set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY} )
endif()
else()
find_library(OPENSSL_SSL_LIBRARY
NAMES
ssl${_OPENSSL_NAME_POSTFIX}
ssleay32
ssleay32MD
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
HINTS
${_OPENSSL_LIBDIR}
${_OPENSSL_LIBRARY_DIRS}
PATH_SUFFIXES
lib lib64
)
find_library(OPENSSL_CRYPTO_LIBRARY
NAMES
crypto${_OPENSSL_NAME_POSTFIX}
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
HINTS
${_OPENSSL_LIBDIR}
${_OPENSSL_LIBRARY_DIRS}
PATH_SUFFIXES
lib lib64
)
mark_as_advanced(OPENSSL_CRYPTO_LIBRARY OPENSSL_SSL_LIBRARY)
endif()
set(OPENSSL_SSL_LIBRARIES ${OPENSSL_SSL_LIBRARY})
set(OPENSSL_CRYPTO_LIBRARIES ${OPENSSL_CRYPTO_LIBRARY})
set(OPENSSL_LIBRARIES ${OPENSSL_SSL_LIBRARIES} ${OPENSSL_CRYPTO_LIBRARIES} )
_OpenSSL_test_and_find_dependencies("${OPENSSL_SSL_LIBRARY}" "${OPENSSL_CRYPTO_LIBRARY}")
if(_OpenSSL_has_dependencies)
_OpenSSL_add_dependencies( OPENSSL_SSL_LIBRARIES )
_OpenSSL_add_dependencies( OPENSSL_CRYPTO_LIBRARIES )
_OpenSSL_add_dependencies( OPENSSL_LIBRARIES )
endif()
function(from_hex HEX DEC)
string(TOUPPER "${HEX}" HEX)
set(_res 0)
string(LENGTH "${HEX}" _strlen)
while (_strlen GREATER 0)
math(EXPR _res "${_res} * 16")
string(SUBSTRING "${HEX}" 0 1 NIBBLE)
string(SUBSTRING "${HEX}" 1 -1 HEX)
if (NIBBLE STREQUAL "A")
math(EXPR _res "${_res} + 10")
elseif (NIBBLE STREQUAL "B")
math(EXPR _res "${_res} + 11")
elseif (NIBBLE STREQUAL "C")
math(EXPR _res "${_res} + 12")
elseif (NIBBLE STREQUAL "D")
math(EXPR _res "${_res} + 13")
elseif (NIBBLE STREQUAL "E")
math(EXPR _res "${_res} + 14")
elseif (NIBBLE STREQUAL "F")
math(EXPR _res "${_res} + 15")
else()
math(EXPR _res "${_res} + ${NIBBLE}")
endif()
string(LENGTH "${HEX}" _strlen)
endwhile()
set(${DEC} ${_res} PARENT_SCOPE)
endfunction()
if(OPENSSL_INCLUDE_DIR AND EXISTS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h")
file(STRINGS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" openssl_version_str
REGEX "^#[\t ]*define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")
if(openssl_version_str)
# The version number is encoded as 0xMNNFFPPS: major minor fix patch status
# The status gives if this is a developer or prerelease and is ignored here.
# Major, minor, and fix directly translate into the version numbers shown in
# the string. The patch field translates to the single character suffix that
# indicates the bug fix state, which 00 -> nothing, 01 -> a, 02 -> b and so
# on.
string(REGEX REPLACE "^.*OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F]).*$"
"\\1;\\2;\\3;\\4;\\5" OPENSSL_VERSION_LIST "${openssl_version_str}")
list(GET OPENSSL_VERSION_LIST 0 OPENSSL_VERSION_MAJOR)
list(GET OPENSSL_VERSION_LIST 1 OPENSSL_VERSION_MINOR)
from_hex("${OPENSSL_VERSION_MINOR}" OPENSSL_VERSION_MINOR)
list(GET OPENSSL_VERSION_LIST 2 OPENSSL_VERSION_FIX)
from_hex("${OPENSSL_VERSION_FIX}" OPENSSL_VERSION_FIX)
list(GET OPENSSL_VERSION_LIST 3 OPENSSL_VERSION_PATCH)
if (NOT OPENSSL_VERSION_PATCH STREQUAL "00")
from_hex("${OPENSSL_VERSION_PATCH}" _tmp)
# 96 is the ASCII code of 'a' minus 1
math(EXPR OPENSSL_VERSION_PATCH_ASCII "${_tmp} + 96")
unset(_tmp)
# Once anyone knows how OpenSSL would call the patch versions beyond 'z'
# this should be updated to handle that, too. This has not happened yet
# so it is simply ignored here for now.
string(ASCII "${OPENSSL_VERSION_PATCH_ASCII}" OPENSSL_VERSION_PATCH_STRING)
endif ()
set(OPENSSL_VERSION "${OPENSSL_VERSION_MAJOR}.${OPENSSL_VERSION_MINOR}.${OPENSSL_VERSION_FIX}${OPENSSL_VERSION_PATCH_STRING}")
else ()
# Since OpenSSL 3.0.0, the new version format is MAJOR.MINOR.PATCH and
# a new OPENSSL_VERSION_STR macro contains exactly that
file(STRINGS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" OPENSSL_VERSION_STR
REGEX "^#[\t ]*define[\t ]+OPENSSL_VERSION_STR[\t ]+\"([0-9])+\\.([0-9])+\\.([0-9])+\".*")
string(REGEX REPLACE "^.*OPENSSL_VERSION_STR[\t ]+\"([0-9]+\\.[0-9]+\\.[0-9]+)\".*$"
"\\1" OPENSSL_VERSION_STR "${OPENSSL_VERSION_STR}")
set(OPENSSL_VERSION "${OPENSSL_VERSION_STR}")
unset(OPENSSL_VERSION_STR)
endif ()
endif ()
foreach(_comp IN LISTS OpenSSL_FIND_COMPONENTS)
if(_comp STREQUAL "Crypto")
if(EXISTS "${OPENSSL_INCLUDE_DIR}" AND
(EXISTS "${OPENSSL_CRYPTO_LIBRARY}" OR
EXISTS "${LIB_EAY_LIBRARY_DEBUG}" OR
EXISTS "${LIB_EAY_LIBRARY_RELEASE}")
)
set(OpenSSL_${_comp}_FOUND TRUE)
else()
set(OpenSSL_${_comp}_FOUND FALSE)
endif()
elseif(_comp STREQUAL "SSL")
if(EXISTS "${OPENSSL_INCLUDE_DIR}" AND
(EXISTS "${OPENSSL_SSL_LIBRARY}" OR
EXISTS "${SSL_EAY_LIBRARY_DEBUG}" OR
EXISTS "${SSL_EAY_LIBRARY_RELEASE}")
)
set(OpenSSL_${_comp}_FOUND TRUE)
else()
set(OpenSSL_${_comp}_FOUND FALSE)
endif()
else()
message(WARNING "${_comp} is not a valid OpenSSL component")
set(OpenSSL_${_comp}_FOUND FALSE)
endif()
endforeach()
unset(_comp)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(OpenSSL
REQUIRED_VARS
OPENSSL_CRYPTO_LIBRARY
OPENSSL_INCLUDE_DIR
VERSION_VAR
OPENSSL_VERSION
HANDLE_COMPONENTS
FAIL_MESSAGE
"Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR"
)
mark_as_advanced(OPENSSL_INCLUDE_DIR)
if(OPENSSL_FOUND)
if(NOT TARGET OpenSSL::Crypto AND
(EXISTS "${OPENSSL_CRYPTO_LIBRARY}" OR
EXISTS "${LIB_EAY_LIBRARY_DEBUG}" OR
EXISTS "${LIB_EAY_LIBRARY_RELEASE}")
)
add_library(OpenSSL::Crypto UNKNOWN IMPORTED)
set_target_properties(OpenSSL::Crypto PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_INCLUDE_DIR}")
if(EXISTS "${OPENSSL_CRYPTO_LIBRARY}")
set_target_properties(OpenSSL::Crypto PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${OPENSSL_CRYPTO_LIBRARY}")
endif()
if(EXISTS "${LIB_EAY_LIBRARY_RELEASE}")
set_property(TARGET OpenSSL::Crypto APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(OpenSSL::Crypto PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
IMPORTED_LOCATION_RELEASE "${LIB_EAY_LIBRARY_RELEASE}")
endif()
if(EXISTS "${LIB_EAY_LIBRARY_DEBUG}")
set_property(TARGET OpenSSL::Crypto APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(OpenSSL::Crypto PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
IMPORTED_LOCATION_DEBUG "${LIB_EAY_LIBRARY_DEBUG}")
endif()
_OpenSSL_target_add_dependencies(OpenSSL::Crypto)
endif()
if(NOT TARGET OpenSSL::SSL AND
(EXISTS "${OPENSSL_SSL_LIBRARY}" OR
EXISTS "${SSL_EAY_LIBRARY_DEBUG}" OR
EXISTS "${SSL_EAY_LIBRARY_RELEASE}")
)
add_library(OpenSSL::SSL UNKNOWN IMPORTED)
set_target_properties(OpenSSL::SSL PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_INCLUDE_DIR}")
if(EXISTS "${OPENSSL_SSL_LIBRARY}")
set_target_properties(OpenSSL::SSL PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${OPENSSL_SSL_LIBRARY}")
endif()
if(EXISTS "${SSL_EAY_LIBRARY_RELEASE}")
set_property(TARGET OpenSSL::SSL APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(OpenSSL::SSL PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
IMPORTED_LOCATION_RELEASE "${SSL_EAY_LIBRARY_RELEASE}")
endif()
if(EXISTS "${SSL_EAY_LIBRARY_DEBUG}")
set_property(TARGET OpenSSL::SSL APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(OpenSSL::SSL PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
IMPORTED_LOCATION_DEBUG "${SSL_EAY_LIBRARY_DEBUG}")
endif()
if(TARGET OpenSSL::Crypto)
set_target_properties(OpenSSL::SSL PROPERTIES
INTERFACE_LINK_LIBRARIES OpenSSL::Crypto)
endif()
_OpenSSL_target_add_dependencies(OpenSSL::SSL)
endif()
if("${OPENSSL_VERSION_MAJOR}.${OPENSSL_VERSION_MINOR}.${OPENSSL_VERSION_FIX}" VERSION_GREATER_EQUAL "0.9.8")
if(MSVC)
if(EXISTS "${OPENSSL_INCLUDE_DIR}")
set(_OPENSSL_applink_paths PATHS ${OPENSSL_INCLUDE_DIR})
endif()
find_file(OPENSSL_APPLINK_SOURCE
NAMES
openssl/applink.c
${_OPENSSL_applink_paths}
NO_DEFAULT_PATH)
if(OPENSSL_APPLINK_SOURCE)
set(_OPENSSL_applink_interface_srcs ${OPENSSL_APPLINK_SOURCE})
endif()
endif()
if(NOT TARGET OpenSSL::applink)
add_library(OpenSSL::applink INTERFACE IMPORTED)
set_property(TARGET OpenSSL::applink APPEND
PROPERTY INTERFACE_SOURCES
${_OPENSSL_applink_interface_srcs})
endif()
endif()
endif()
# Restore the original find library ordering
if(OPENSSL_USE_STATIC_LIBS)
set(CMAKE_FIND_LIBRARY_SUFFIXES ${_openssl_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
endif()
unset(_OPENSSL_FIND_PATH_SUFFIX)
unset(_OPENSSL_NAME_POSTFIX)
unset(_OpenSSL_extra_static_deps)
unset(_OpenSSL_has_dependency_dl)
unset(_OpenSSL_has_dependency_threads)
unset(_OpenSSL_has_dependency_zlib)
+35
View File
@@ -0,0 +1,35 @@
if (CMAKE_VERSION VERSION_LESS "3.16.0")
if (MSVC)
# Specify the maximum PreCompiled Header memory allocation limit
# Fixes a compiler-problem when using PCH - the /Ym flag is adjusted by the compiler in MSVC2012,
# hence we need to set an upper limit with /Zm to avoid discrepancies)
# (And yes, this is a verified, unresolved bug with MSVC... *sigh*)
#
# Note: This workaround was verified to be required on MSVC 2017 as well
set(COTIRE_PCH_MEMORY_SCALING_FACTOR 500)
endif ()
include(cotire)
function(ADD_CXX_PCH TARGET_NAME_LIST PCH_HEADER)
# Use the header for every target
foreach (TARGET_NAME ${TARGET_NAME_LIST})
# Disable unity builds
set_target_properties(${TARGET_NAME} PROPERTIES COTIRE_ADD_UNITY_BUILD OFF)
# Set the prefix header
set_target_properties(${TARGET_NAME} PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT ${PCH_HEADER})
# Workaround for cotire bug: https://github.com/sakra/cotire/issues/138
set_property(TARGET ${TARGET_NAME} PROPERTY CXX_STANDARD 14)
endforeach ()
cotire(${TARGET_NAME_LIST})
endfunction(ADD_CXX_PCH)
else()
function(ADD_CXX_PCH TARGET_NAME_LIST PCH_HEADER)
foreach(TARGET_NAME ${TARGET_NAME_LIST})
target_precompile_headers(${TARGET_NAME} PRIVATE ${PCH_HEADER})
endforeach()
endfunction(ADD_CXX_PCH)
endif()
+51
View File
@@ -0,0 +1,51 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
macro(GroupSources dir)
# Skip this if WITH_SOURCE_TREE is not set (empty string).
if (NOT ${WITH_SOURCE_TREE} STREQUAL "")
# Include all header and c files
file(GLOB_RECURSE elements RELATIVE ${dir} *.h *.hpp *.c *.cpp *.cc)
foreach(element ${elements})
# Extract filename and directory
get_filename_component(element_name ${element} NAME)
get_filename_component(element_dir ${element} DIRECTORY)
if (NOT ${element_dir} STREQUAL "")
# If the file is in a subdirectory use it as source group.
if (${WITH_SOURCE_TREE} STREQUAL "flat")
# Build flat structure by using only the first subdirectory.
string(FIND ${element_dir} "/" delemiter_pos)
if (NOT ${delemiter_pos} EQUAL -1)
string(SUBSTRING ${element_dir} 0 ${delemiter_pos} group_name)
source_group("${group_name}" FILES ${dir}/${element})
else()
# Build hierarchical structure.
# File is in root directory.
source_group("${element_dir}" FILES ${dir}/${element})
endif()
else()
# Use the full hierarchical structure to build source_groups.
string(REPLACE "/" "\\" group_name ${element_dir})
source_group("${group_name}" FILES ${dir}/${element})
endif()
else()
# If the file is in the root directory, place it in the root source_group.
source_group("\\" FILES ${dir}/${element})
endif()
endforeach()
endif()
endmacro()
if (WITH_SOURCE_TREE STREQUAL "hierarchical-folders")
# Use folders
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
endif()
+54
View File
@@ -0,0 +1,54 @@
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
option(SERVERS "Build worldserver and bnetserver" 1)
set(SCRIPTS_AVAILABLE_OPTIONS none static dynamic minimal-static minimal-dynamic)
# Log a fatal error when the value of the SCRIPTS variable isn't a valid option.
if (SCRIPTS)
list (FIND SCRIPTS_AVAILABLE_OPTIONS "${SCRIPTS}" SCRIPTS_INDEX)
if (${SCRIPTS_INDEX} EQUAL -1)
message(FATAL_ERROR "The value (${SCRIPTS}) of your SCRIPTS variable is invalid! "
"Allowed values are: ${SCRIPTS_AVAILABLE_OPTIONS} if you still "
"have problems search on forum for TCE00019.")
endif()
endif()
set(SCRIPTS "static" CACHE STRING "Build core with scripts")
set_property(CACHE SCRIPTS PROPERTY STRINGS ${SCRIPTS_AVAILABLE_OPTIONS})
# Build a list of all script modules when -DSCRIPT="custom" is selected
GetScriptModuleList(SCRIPT_MODULE_LIST)
foreach(SCRIPT_MODULE ${SCRIPT_MODULE_LIST})
ScriptModuleNameToVariable(${SCRIPT_MODULE} SCRIPT_MODULE_VARIABLE)
set(${SCRIPT_MODULE_VARIABLE} "default" CACHE STRING "Build type of the ${SCRIPT_MODULE} module.")
set_property(CACHE ${SCRIPT_MODULE_VARIABLE} PROPERTY STRINGS default disabled static dynamic)
endforeach()
option(TOOLS "Build map/vmap/mmap extraction/assembler tools" 1)
option(USE_SCRIPTPCH "Use precompiled headers when compiling scripts" 1)
option(USE_COREPCH "Use precompiled headers when compiling servers" 1)
option(WITH_DYNAMIC_LINKING "Enable dynamic library linking." 0)
IsDynamicLinkingRequired(WITH_DYNAMIC_LINKING_FORCED)
if (WITH_DYNAMIC_LINKING AND WITH_DYNAMIC_LINKING_FORCED)
set(WITH_DYNAMIC_LINKING_FORCED OFF)
endif()
if (WITH_DYNAMIC_LINKING OR WITH_DYNAMIC_LINKING_FORCED)
set(BUILD_SHARED_LIBS ON)
else()
set(BUILD_SHARED_LIBS OFF)
endif()
option(WITH_WARNINGS "Show all warnings during compile" 0)
option(WITH_COREDEBUG "Include additional debug-code in core" 0)
set(WITH_SOURCE_TREE "hierarchical" CACHE STRING "Build the source tree for IDE's.")
set_property(CACHE WITH_SOURCE_TREE PROPERTY STRINGS no flat hierarchical hierarchical-folders)
option(WITHOUT_GIT "Disable the GIT testing routines" 0)
option(WITH_CPR "Enable CPR dep (curl wrapper)" 0)
+23
View File
@@ -0,0 +1,23 @@
# from cmake wiki
IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
STRING(REGEX REPLACE "\n" ";" files "${files}")
FOREACH(file ${files})
MESSAGE(STATUS "Uninstalling \"${file}\"")
IF(EXISTS "${file}")
EXEC_PROGRAM(
"@CMAKE_COMMAND@" ARGS "-E remove \"${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval
)
IF("${rm_retval}" STREQUAL 0)
ELSE("${rm_retval}" STREQUAL 0)
MESSAGE(FATAL_ERROR "Problem when removing \"${file}\"")
ENDIF("${rm_retval}" STREQUAL 0)
ELSE(EXISTS "${file}")
MESSAGE(STATUS "File \"${file}\" does not exist.")
ENDIF(EXISTS "${file}")
ENDFOREACH(file)
+38
View File
@@ -0,0 +1,38 @@
# set default configuration directory
if( NOT CONF_DIR )
set(CONF_DIR ${CMAKE_INSTALL_PREFIX}/etc)
message(STATUS "UNIX: Using default configuration directory")
endif()
# set default library directory
if( NOT LIBSDIR )
set(LIBSDIR ${CMAKE_INSTALL_PREFIX}/lib)
message(STATUS "UNIX: Using default library directory")
endif()
# configure uninstaller
configure_file(
"${CMAKE_SOURCE_DIR}/cmake/platform/cmake_uninstall.in.cmake"
"${CMAKE_BINARY_DIR}/cmake_uninstall.cmake"
@ONLY
)
message(STATUS "UNIX: Configuring uninstall target")
# create uninstaller target (allows for using "make uninstall")
add_custom_target(uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_BINARY_DIR}/cmake_uninstall.cmake"
)
message(STATUS "UNIX: Created uninstall target")
message(STATUS "UNIX: Detected compiler: ${CMAKE_C_COMPILER}")
if(CMAKE_C_COMPILER MATCHES "gcc" OR CMAKE_C_COMPILER_ID STREQUAL "GNU")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/gcc/settings.cmake)
elseif(CMAKE_C_COMPILER MATCHES "icc")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/icc/settings.cmake)
elseif(CMAKE_C_COMPILER MATCHES "clang" OR CMAKE_C_COMPILER_ID MATCHES "Clang")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/clang/settings.cmake)
else()
target_compile_definitions(trinity-compile-option-interface
INTERFACE
-D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}")
endif()
+14
View File
@@ -0,0 +1,14 @@
add_definitions(-D_WIN32_WINNT=0x0601)
add_definitions(-DWIN32_LEAN_AND_MEAN)
add_definitions(-DNOMINMAX)
# set up output paths for executable binaries (.exe-files, and .dll-files on DLL-capable platforms)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$<CONFIG>")
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/msvc/settings.cmake)
elseif (CMAKE_CXX_PLATFORM_ID MATCHES "MinGW")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/mingw/settings.cmake)
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
include(${CMAKE_SOURCE_DIR}/cmake/compiler/clang/settings.cmake)
endif()
+128
View File
@@ -0,0 +1,128 @@
# output generic information about the core and buildtype chosen
message("")
message("* TrinityCore revision : ${rev_hash} ${rev_date} (${rev_branch} branch)")
if( UNIX )
message("* TrinityCore buildtype : ${CMAKE_BUILD_TYPE}")
endif()
message("")
# output information about installation-directories and locations
message("* Install core to : ${CMAKE_INSTALL_PREFIX}")
if( UNIX )
message("* Install libraries to : ${LIBSDIR}")
message("* Install configs to : ${CONF_DIR}")
endif()
message("")
# Show infomation about the options selected during configuration
if( SERVERS )
message("* Build world/auth : Yes (default)")
else()
message("* Build world/bnetserver : No")
endif()
if(SCRIPTS AND (NOT SCRIPTS STREQUAL "none"))
message("* Build with scripts : Yes (${SCRIPTS})")
else()
message("* Build with scripts : No")
endif()
if( TOOLS )
message("* Build map/vmap tools : Yes (default)")
else()
message("* Build map/vmap tools : No")
endif()
if( USE_COREPCH )
message("* Build core w/PCH : Yes (default)")
else()
message("* Build core w/PCH : No")
endif()
if( USE_SCRIPTPCH )
message("* Build scripts w/PCH : Yes (default)")
else()
message("* Build scripts w/PCH : No")
endif()
if( WITH_WARNINGS )
message("* Show all warnings : Yes")
else()
message("* Show compile-warnings : No (default)")
endif()
if( WITH_COREDEBUG )
message("")
message(" *** WITH_COREDEBUG - WARNING!")
message(" *** additional core debug logs have been enabled!")
message(" *** this setting doesn't help to get better crash logs!")
message(" *** in case you are searching for better crash logs use")
message(" *** -DCMAKE_BUILD_TYPE=RelWithDebug")
message(" *** DO NOT ENABLE IT UNLESS YOU KNOW WHAT YOU'RE DOING!")
message("* Use coreside debug : Yes")
add_definitions(-DTRINITY_DEBUG)
else()
message("* Use coreside debug : No (default)")
endif()
if( NOT WITH_SOURCE_TREE STREQUAL "no" )
message("* Show source tree : Yes (${WITH_SOURCE_TREE})")
else()
message("* Show source tree : No")
endif()
if ( WITHOUT_GIT )
message("* Use GIT revision hash : No")
message("")
message(" *** WITHOUT_GIT - WARNING!")
message(" *** By choosing the WITHOUT_GIT option you have waived all rights for support,")
message(" *** and accept that or all requests for support or assistance sent to the core")
message(" *** developers will be rejected. This due to that we will be unable to detect")
message(" *** what revision of the codebase you are using in a proper way.")
message(" *** We remind you that you need to use the repository codebase and a supported")
message(" *** version of git for the revision-hash to work, and be allowede to ask for")
message(" *** support if needed.")
else()
message("* Use GIT revision hash : Yes (default)")
endif()
if ( NOJEM )
message("")
message(" *** NOJEM - WARNING!")
message(" *** jemalloc linking has been disabled!")
message(" *** Please note that this is for DEBUGGING WITH VALGRIND only!")
message(" *** DO NOT DISABLE IT UNLESS YOU KNOW WHAT YOU'RE DOING!")
elseif ( VALGRIND )
message("")
message(" *** VALGRIND - WARNING!")
message(" *** jemalloc will be configured to support Valgrind")
message(" *** Please specify the valgrind include directory in VALGRIND_INCLUDE_DIR option if you get build errors")
message(" *** Please note that this is for DEBUGGING WITH VALGRIND only!")
add_definitions(-DJEMALLOC_VALGRIND)
endif()
if ( HELGRIND )
message("")
message(" *** HELGRIND - WARNING!")
message(" *** Please specify the valgrind include directory in VALGRIND_INCLUDE_DIR option if you get build errors")
message(" *** Please note that this is for DEBUGGING WITH HELGRIND only!")
add_definitions(-DHELGRIND)
endif()
if (BUILD_SHARED_LIBS)
message("")
message(" *** WITH_DYNAMIC_LINKING - INFO!")
message(" *** Will link against shared libraries!")
message(" *** Please note that this is an experimental feature!")
if (WITH_DYNAMIC_LINKING_FORCED)
message("")
message(" *** Dynamic linking was enforced through a dynamic script module!")
endif()
add_definitions(-DTRINITY_API_USE_DYNAMIC_LINKING)
WarnAboutSpacesInBuildPath()
endif()
message("")
+31
View File
@@ -0,0 +1,31 @@
/* Copyright (C) 2009 Sun Microsystems, Inc
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; version 2 of the License.
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 St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Check stack direction (0-down, 1-up) */
int f(int *a)
{
int b;
return(&b > a)?1:0;
}
/*
Prevent compiler optimizations by calling function
through pointer.
*/
volatile int (*ptr_f)(int *) = f;
int main()
{
int a;
return ptr_f(&a);
}
+1
View File
@@ -0,0 +1 @@
node_modules*/
+82
View File
@@ -0,0 +1,82 @@
# ServerRelay
Server Relay between world of warcraft world channel(AshamaneCore) and Discord.
### CREDITS
* Made by : __DEVIL1234__
* E-mail : __ingerasu1234@yahoo.com__.
* Credits for helping me : __Traesh__ from AshamaneProject
* Credits to guys with exceptional packages that simplified the process of making this project to happen
### Installation
To install this ServerRelay on your server(is more securely to run in same host with worldserver or internal on lan) you need to install Node.JS package and have setup a discord server and bot for it. Is already many tutorials how to setup this already on internet (google it bro). Tip : set the discordapp on developer mode, for id's right-click on channel's and select copy id.
SPECIAL REQUIREMENT : compile the worldserver with -DCPR=1 argument on cmake. ( will take a longer time to configure)
Recommended version of Node.JS : __v8.11.3__. Upper version is your risk to use.
1. Commands:
```javascript
//That will install all packages needed from package.json and will be ready to use
npm install
```
2. Configure the config.json file with your channels id and token from bot. The rest is preferable to not edit exception is the prefix for send command. Like this :
```javascript
{
"token": "BOT-TOKEN",
"channel_id": "RELAY-CHAT-ID",
"staff_channel_ID" : "STAFF-CHANNEL-ID",
"post_url_server_message_world": "http://127.0.0.1:8082/sendChannelMessage/",
"post_url_server_message_alliance" : "http://127.0.0.1:8082/sendChannelMessage/0",
"post_url_server_message_horde" : "http://127.0.0.1:8082/sendChannelMessage/1",
"post_url_server_command": "http://127.0.0.1:8082/command",
"post_port": "8082",
"post_token": "TOKEN FROM WORLDSERVER.CONF ON WorldREST.AuthToken, THIS ONE NEED TO MATCH HERE",
"channel_horde" : "world_h", // I RECOMMEND TO NOT CHANGE IT
"channel_alliance": "world_a", // I RECOMMEND TO NOT CHANGE IT
"allow_interactions" : "0", // IF YOU SET TO 1, YOU NEED TO ENABLE IN WORLDSERVER.CONF THIS ONE : AllowTwoSide.Interaction.Channel.
"channel_world" : "world", // I RECOMMEND TO NOT CHANGE IT
"command_prefix" : "." // IS USED ON staff channel for purge command(delete the message on channels) and send command for ingame commands(is same one from console)
}
```
3. Configure the roles:
```javascript
Open the server.js file with txt editor and read the comments line numbers : 13 -> 16
```
4. Running the server :
* Windows :
<br /> WARNING: WILL RUN WITHOUT CMD PROMPT TO BE SHOWN
```javascript
Run the file windows.vbs
```
* Linux :
```javascript
chmod +x run.sh
./linux.sh &
// OPTIONALY CAND SET A CRONTAB WITH run.sh. THE SERVER IF IS WILL CRASH, THE NODEMON WILL TAKE OF SERVER.JS. IF YOU WANT TO SETUP CRONTAB ON THE END NOT SPECIFY `</dev/null>` BECAUSE IS ALREADY SPECIFIED ON linux.sh
```
### Commands accessible on this discord bot
* Send
```javascript
(prefix)send argument(commands accessible on worldserver console)
```
* EXAMPLE :
```javascript
.send help // will return all commands available
```
* Purge
```javascript
(prefix)purge <1-100> (will delete the message on channel(can be used on any channel)
```
* EXAMPLE
* EXAMPLE :
```javascript
.purge 10 // delete 10 messages from channel
```
### Support
If you need support for this relay contact me on discord server Ashamane under the username : __devil1234__.
If you want to support with donations contact me same like up but on direct message/private message.
+15
View File
@@ -0,0 +1,15 @@
{
"token": "",
"channel_id": "",
"staff_channel_ID" : "",
"post_url_server_message_world": "http://127.0.0.1:8082/sendChannelMessage/",
"post_url_server_message_alliance" : "http://127.0.0.1:8082/sendChannelMessage/0",
"post_url_server_message_horde" : "http://127.0.0.1:8082/sendChannelMessage/1",
"post_url_server_command": "http://127.0.0.1:8082/command",
"post_token": "",
"channel_horde" : "world_h",
"channel_alliance": "world_a",
"allow_interactions" : "0",
"channel_world" : "world",
"command_prefix" : "."
}
+1
View File
@@ -0,0 +1 @@
nodemon > /dev/null
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
{
"name": "server-relay",
"version": "1.0.0",
"description": "Server Relay between world of warcraft channel(AshamaneCore) and Discord",
"main": "server.js",
"author": {
"name": "DEVIL1234"
},
"nodemonConfig":{
"ignore": ["config.json", "node_modules/*"]
},
"dependencies": {
"discord.js": "^11.3.2",
"http": "0.0.0",
"is-empty": "^1.2.0",
"node-emoji": "^1.8.1",
"nodemon": "^1.18.3",
"parse-json": "^4.0.0",
"request": "^2.87.0",
"request-promise": "^4.2.2"
}
}
@@ -0,0 +1,2 @@
@echo off
nodemon > NUL
+244
View File
@@ -0,0 +1,244 @@
/* requirements */
var Discord = require("discord.js");
var config = require("./config.json")
var client = new Discord.Client();
const request = require('request');
const http = require('http');
var rp = require('request-promise');
const parseJson = require('parse-json');
var emoji = require('node-emoji');
var empty = require('is-empty');
// CONFIGURE THE ROLES NEEDED FOR GM Logo
// If you want more roles added just do like this (append to original one on line 95 and 195(optionaly, for send command) with
// || message.member.roles.find("name", role_3+) and add const role_number here.
// If you want just to change role name, modify the attribute below . Example : Admin -> Your role name
role_1 = "Owner";
role_2 = "GameMasters";
/* Ready the client */
client.on('ready', () => {
console.log('I am ready!');
client.user.setPresence({game: {name: "WORD PORN", type: 0}});
client.user.setStatus('dnd');
//console.log(`Logged in as ${client.user.tag}!`);
var server = http.createServer(OnWorldMessage);
OnDiscordMessage();
Commands();
server.listen(8083);
});
client.on("disconnected", function () { process.exit(1); });
/*
* Handle message in the way "World => Discord"
*/
function OnWorldMessage(request, response) {
if (request.method != "POST") {
response.writeHead(404);
response.end();
return;
}
try {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
//console.log(body);
/*Send the message to discord*/
// Parse the json message to can return part from it
var myJSON = JSON.parse(body);
//console.log(string);
// send to discord channel id and the json text
switch(config.allow_interactions)
{
case "1":
client.channels.get(config.channel_id).send(myJSON.text);
break;
case "0":
var string = "[" + myJSON.channel + "]" + " " + myJSON.text;
client.channels.get(config.channel_id).send(string);
break;
}
response.writeHead(200);
response.end();
});
}
catch (e) {
console.log(e);
response.writeHead(500);
response.end();
}
}
/*
* Handle message in the way "Discord => World"
*/
function OnDiscordMessage() {
client.on('message', async message => {
if (message.author.bot) return;
if (message.channel.type === "dm") return;
// SEND TO WORLD CHANNEL
// showGMlogo bollean
if(message.channel.id === config.channel_id){
if(message.member.roles.find("name", role_1) || message.member.roles.find("name", role_2)) {var gmLOGO = '1'} else { gmLOGO = "0"};
const messageArray = message.content;
const author = message.member.user.username;
const message_emoji_replace = emoji.replace(messageArray, (emoji) => `${emoji.key}`);
// world channel
let json_world = JSON.stringify({"senderName":author,"channelName":config.channel_world,"message": message_emoji_replace, "showGMLogo": gmLOGO});
// world_a channel
let json_world_a = JSON.stringify({"senderName":author,"channelName":config.channel_alliance,"message": message_emoji_replace, "showGMLogo": gmLOGO});
// world_h channel
let json_world_h = JSON.stringify({"senderName":author,"channelName":config.channel_horde,"message": message_emoji_replace, "showGMLogo": gmLOGO});
// allow interactions between horde and alliance on world channel's
switch (config.allow_interactions){
case "1":
var url_0 = config.post_url_server_message_world + "0";
var url_1 = config.post_url_server_message_world + "1";
console.log(url_0);
var auth = { 'Authorization': config.post_token};
request.post({url:url_0, form: json_world, headers: auth}, function(err, httpResponse,body)
{
if(err) {
return console.log(err);
}
//console.log('post Suceess the response is:', body);
});
var auth = { 'Authorization': config.post_token};
request.post({url:url_1, form: json_world, headers: auth}, function(err, httpResponse,body)
{
if(err) {
return console.log(err);
}
//console.log('post Suceess the response is:', body);
});
break;
case "0":
var auth = { 'Authorization': config.post_token};
request.post({url:config.post_url_server_message_alliance, form: json_world_a, headers: auth}, function(err, httpResponse,body)
{
if(err) {
return console.log(err);
}
console.log('post Suceess the response is:', body);
});
request.post({url:config.post_url_server_message_horde, form: json_world_h, headers: auth}, function(err, httpResponse,body)
{
if(err) {
return console.log(err);
}
//console.log('post Suceess the response is:', body);
});
break;
// default:
};
};
});
};
/*
* Handle the commands
*/
function Commands() {
client.on('message', async message => {
if (message.author.bot) return;
if (message.channel.type === "dm") return;
const args = message.content.slice(config.command_prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(message.content.indexOf(config.command_prefix) !== 0) return;
// COMMAND POST COMMANDS
if(command === "purge") {
// This command removes all messages from all users in the channel, up to 100.
// get the delete count, as an actual number.
const deleteCount = parseInt(args[0], 10);
// Ooooh nice, combined conditions. <3
if(!deleteCount || deleteCount < 2 || deleteCount > 1000)
return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
// So we get our messages, and delete them. Simple enough, right?
const fetched = await message.channel.fetchMessages({limit: deleteCount});
message.channel.bulkDelete(fetched)
.catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
};
if(message.channel.id === config.staff_channel_ID){
if(message.member.roles.find("name", role_1) || message.member.roles.find("name", role_2))
{
if(command === "send") {
const sendCommand = args.join(" ");
message.delete().catch(O_o=>{});
//let json = {"command":sendCommand}
//console.log(args.length);
if (args != null && args.length > 0)
{
//let json_string = JSON.stringify(json)
var auth = { 'Authorization': config.post_token}
var options = {method: 'POST', uri: config.post_url_server_command, body: {"command":sendCommand} ,headers: auth, json: true, resolveWithFullResponse: true, needReadable: true};
rp(options).then(function (response) {
//console.log(response);
var myJSONString = JSON.stringify(response.body);
//console.log(myJSONString);
var myEscapedJSONString = myJSONString.replace(/\\r/g, "").replace(/\\n/g, "").replace(/\s\s+/g, " ");
if (myEscapedJSONString === myJSONString)
{
var b = JSON.parse(myEscapedJSONString);
//console.log("this is b:", b);
//console.log(b.message);
message.channel.send("The command was sent to worldserver.");
} else {
var a = JSON.parse(JSON.parse(myEscapedJSONString));
//console.log("this is a :" ,a)
//console.log(a.message);
message.channel.send("Your command response is: " + a.message);
}
}).catch(function (err) {
console.log(err)
})
}
else {
message.channel.send("You can't send emty command");
};
};
} else { message.channel.send("Not enough permission to use this command. Contact Admin or Gamemaster to ban you :smile:"); };
};
});
}
client.login(config.token);
+3
View File
@@ -0,0 +1,3 @@
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & ".\run-server-scripts\windows.bat" & Chr(34), 0
Set WshShell = Nothing
@@ -0,0 +1,590 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v2.0",
"signature": "fdbd75ff1a1b8362cf270a3142b4fe1db3a66bc1"
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v2.0": {
"AshamaneDependencyManager/1.0.0": {
"dependencies": {
"System.Runtime.Serialization.Json": "4.3.0"
},
"runtime": {
"AshamaneDependencyManager.dll": {}
}
},
"Microsoft.NETCore.Targets/1.1.0": {},
"System.Collections/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Collections.Concurrent/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Diagnostics.Tracing": "4.3.0",
"System.Globalization": "4.3.0",
"System.Reflection": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Threading": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.Diagnostics.Debug/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Diagnostics.Tools/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Diagnostics.Tracing/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Globalization/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.IO/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.IO.FileSystem/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.IO": "4.3.0",
"System.IO.FileSystem.Primitives": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Handles": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.IO.FileSystem.Primitives/4.3.0": {
"dependencies": {
"System.Runtime": "4.3.0"
}
},
"System.Linq/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0"
}
},
"System.Private.DataContractSerialization/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Collections.Concurrent": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Globalization": "4.3.0",
"System.IO": "4.3.0",
"System.Linq": "4.3.0",
"System.Reflection": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Emit.Lightweight": "4.3.0",
"System.Reflection.Extensions": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Reflection.TypeExtensions": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Runtime.Serialization.Primitives": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Text.Encoding.Extensions": "4.3.0",
"System.Text.RegularExpressions": "4.3.0",
"System.Threading": "4.3.0",
"System.Threading.Tasks": "4.3.0",
"System.Xml.ReaderWriter": "4.3.0",
"System.Xml.XDocument": "4.3.0",
"System.Xml.XmlDocument": "4.3.0",
"System.Xml.XmlSerializer": "4.3.0"
}
},
"System.Reflection/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.IO": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit/4.3.0": {
"dependencies": {
"System.IO": "4.3.0",
"System.Reflection": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit.ILGeneration/4.3.0": {
"dependencies": {
"System.Reflection": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Emit.Lightweight/4.3.0": {
"dependencies": {
"System.Reflection": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Extensions/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Reflection": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.Primitives/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Reflection.TypeExtensions/4.3.0": {
"dependencies": {
"System.Reflection": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Resources.ResourceManager/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Globalization": "4.3.0",
"System.Reflection": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0"
}
},
"System.Runtime.Extensions/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime.Handles/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime.InteropServices/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Reflection": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Handles": "4.3.0"
}
},
"System.Runtime.Serialization.Json/4.3.0": {
"dependencies": {
"System.IO": "4.3.0",
"System.Private.DataContractSerialization": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Runtime.Serialization.Primitives/4.3.0": {
"dependencies": {
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0"
}
},
"System.Text.Encoding/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Text.Encoding.Extensions/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0",
"System.Text.Encoding": "4.3.0"
}
},
"System.Text.RegularExpressions/4.3.0": {
"dependencies": {
"System.Runtime": "4.3.0"
}
},
"System.Threading/4.3.0": {
"dependencies": {
"System.Runtime": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.Threading.Tasks/4.3.0": {
"dependencies": {
"Microsoft.NETCore.Targets": "1.1.0",
"System.Runtime": "4.3.0"
}
},
"System.Threading.Tasks.Extensions/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Runtime": "4.3.0",
"System.Threading.Tasks": "4.3.0"
}
},
"System.Xml.ReaderWriter/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Globalization": "4.3.0",
"System.IO": "4.3.0",
"System.IO.FileSystem": "4.3.0",
"System.IO.FileSystem.Primitives": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Runtime.InteropServices": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Text.Encoding.Extensions": "4.3.0",
"System.Text.RegularExpressions": "4.3.0",
"System.Threading.Tasks": "4.3.0",
"System.Threading.Tasks.Extensions": "4.3.0"
}
},
"System.Xml.XDocument/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Diagnostics.Tools": "4.3.0",
"System.Globalization": "4.3.0",
"System.IO": "4.3.0",
"System.Reflection": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Threading": "4.3.0",
"System.Xml.ReaderWriter": "4.3.0"
}
},
"System.Xml.XmlDocument/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Diagnostics.Debug": "4.3.0",
"System.Globalization": "4.3.0",
"System.IO": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Text.Encoding": "4.3.0",
"System.Threading": "4.3.0",
"System.Xml.ReaderWriter": "4.3.0"
}
},
"System.Xml.XmlSerializer/4.3.0": {
"dependencies": {
"System.Collections": "4.3.0",
"System.Globalization": "4.3.0",
"System.IO": "4.3.0",
"System.Linq": "4.3.0",
"System.Reflection": "4.3.0",
"System.Reflection.Emit": "4.3.0",
"System.Reflection.Emit.ILGeneration": "4.3.0",
"System.Reflection.Extensions": "4.3.0",
"System.Reflection.Primitives": "4.3.0",
"System.Reflection.TypeExtensions": "4.3.0",
"System.Resources.ResourceManager": "4.3.0",
"System.Runtime": "4.3.0",
"System.Runtime.Extensions": "4.3.0",
"System.Text.RegularExpressions": "4.3.0",
"System.Threading": "4.3.0",
"System.Xml.ReaderWriter": "4.3.0",
"System.Xml.XmlDocument": "4.3.0"
}
}
}
},
"libraries": {
"AshamaneDependencyManager/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
},
"Microsoft.NETCore.Targets/1.1.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-aOZA3BWfz9RXjpzt0sRJJMjAscAUm3Hoa4UWAfceV9UTYxgwZ1lZt5nO2myFf+/jetYQo4uTP7zS8sJY67BBxg==",
"path": "microsoft.netcore.targets/1.1.0",
"hashPath": "microsoft.netcore.targets.1.1.0.nupkg.sha512"
},
"System.Collections/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-3Dcj85/TBdVpL5Zr+gEEBUuFe2icOnLalmEh9hfck1PTYbbyWuZgh4fmm2ysCLTrqLQw6t3TgTyJ+VLp+Qb+Lw==",
"path": "system.collections/4.3.0",
"hashPath": "system.collections.4.3.0.nupkg.sha512"
},
"System.Collections.Concurrent/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-ztl69Xp0Y/UXCL+3v3tEU+lIy+bvjKNUmopn1wep/a291pVPK7dxBd6T7WnlQqRog+d1a/hSsgRsmFnIBKTPLQ==",
"path": "system.collections.concurrent/4.3.0",
"hashPath": "system.collections.concurrent.4.3.0.nupkg.sha512"
},
"System.Diagnostics.Debug/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-ZUhUOdqmaG5Jk3Xdb8xi5kIyQYAA4PnTNlHx1mu9ZY3qv4ELIdKbnL/akbGaKi2RnNUWaZsAs31rvzFdewTj2g==",
"path": "system.diagnostics.debug/4.3.0",
"hashPath": "system.diagnostics.debug.4.3.0.nupkg.sha512"
},
"System.Diagnostics.Tools/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-UUvkJfSYJMM6x527dJg2VyWPSRqIVB0Z7dbjHst1zmwTXz5CcXSYJFWRpuigfbO1Lf7yfZiIaEUesfnl/g5EyA==",
"path": "system.diagnostics.tools/4.3.0",
"hashPath": "system.diagnostics.tools.4.3.0.nupkg.sha512"
},
"System.Diagnostics.Tracing/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-rswfv0f/Cqkh78rA5S8eN8Neocz234+emGCtTF3lxPY96F+mmmUen6tbn0glN6PMvlKQb9bPAY5e9u7fgPTkKw==",
"path": "system.diagnostics.tracing/4.3.0",
"hashPath": "system.diagnostics.tracing.4.3.0.nupkg.sha512"
},
"System.Globalization/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kYdVd2f2PAdFGblzFswE4hkNANJBKRmsfa2X5LG2AcWE1c7/4t0pYae1L8vfZ5xvE2nK/R9JprtToA61OSHWIg==",
"path": "system.globalization/4.3.0",
"hashPath": "system.globalization.4.3.0.nupkg.sha512"
},
"System.IO/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-3qjaHvxQPDpSOYICjUoTsmoq5u6QJAFRUITgeT/4gqkF1bajbSmb1kwSxEA8AHlofqgcKJcM8udgieRNhaJ5Cg==",
"path": "system.io/4.3.0",
"hashPath": "system.io.4.3.0.nupkg.sha512"
},
"System.IO.FileSystem/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-3wEMARTnuio+ulnvi+hkRNROYwa1kylvYahhcLk4HSoVdl+xxTFVeVlYOfLwrDPImGls0mDqbMhrza8qnWPTdA==",
"path": "system.io.filesystem/4.3.0",
"hashPath": "system.io.filesystem.4.3.0.nupkg.sha512"
},
"System.IO.FileSystem.Primitives/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-6QOb2XFLch7bEc4lIcJH49nJN2HV+OC3fHDgsLVsBVBk3Y4hFAnOBGzJ2lUu7CyDDFo9IBWkSsnbkT6IBwwiMw==",
"path": "system.io.filesystem.primitives/4.3.0",
"hashPath": "system.io.filesystem.primitives.4.3.0.nupkg.sha512"
},
"System.Linq/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-5DbqIUpsDp0dFftytzuMmc0oeMdQwjcP/EWxsksIz/w1TcFRkZ3yKKz0PqiYFMmEwPSWw+qNVqD7PJ889JzHbw==",
"path": "system.linq/4.3.0",
"hashPath": "system.linq.4.3.0.nupkg.sha512"
},
"System.Private.DataContractSerialization/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-yDaJ2x3mMmjdZEDB4IbezSnCsnjQ4BxinKhRAaP6kEgL6Bb6jANWphs5SzyD8imqeC/3FxgsuXT6ykkiH1uUmA==",
"path": "system.private.datacontractserialization/4.3.0",
"hashPath": "system.private.datacontractserialization.4.3.0.nupkg.sha512"
},
"System.Reflection/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-KMiAFoW7MfJGa9nDFNcfu+FpEdiHpWgTcS2HdMpDvt9saK3y/G4GwprPyzqjFH9NTaGPQeWNHU+iDlDILj96aQ==",
"path": "system.reflection/4.3.0",
"hashPath": "system.reflection.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-228FG0jLcIwTVJyz8CLFKueVqQK36ANazUManGaJHkO0icjiIypKW7YLWLIWahyIkdh5M7mV2dJepllLyA1SKg==",
"path": "system.reflection.emit/4.3.0",
"hashPath": "system.reflection.emit.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit.ILGeneration/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-59tBslAk9733NXLrUJrwNZEzbMAcu8k344OYo+wfSVygcgZ9lgBdGIzH/nrg3LYhXceynyvTc8t5/GD4Ri0/ng==",
"path": "system.reflection.emit.ilgeneration/4.3.0",
"hashPath": "system.reflection.emit.ilgeneration.4.3.0.nupkg.sha512"
},
"System.Reflection.Emit.Lightweight/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-oadVHGSMsTmZsAF864QYN1t1QzZjIcuKU3l2S9cZOwDdDueNTrqq1yRj7koFfIGEnKpt6NjpL3rOzRhs4ryOgA==",
"path": "system.reflection.emit.lightweight/4.3.0",
"hashPath": "system.reflection.emit.lightweight.4.3.0.nupkg.sha512"
},
"System.Reflection.Extensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-rJkrJD3kBI5B712aRu4DpSIiHRtr6QlfZSQsb0hYHrDCZORXCFjQfoipo2LaMUHoT9i1B7j7MnfaEKWDFmFQNQ==",
"path": "system.reflection.extensions/4.3.0",
"hashPath": "system.reflection.extensions.4.3.0.nupkg.sha512"
},
"System.Reflection.Primitives/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-5RXItQz5As4xN2/YUDxdpsEkMhvw3e6aNveFXUn4Hl/udNTCNhnKp8lT9fnc3MhvGKh1baak5CovpuQUXHAlIA==",
"path": "system.reflection.primitives/4.3.0",
"hashPath": "system.reflection.primitives.4.3.0.nupkg.sha512"
},
"System.Reflection.TypeExtensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-7u6ulLcZbyxB5Gq0nMkQttcdBTx57ibzw+4IOXEfR+sXYQoHvjW5LTLyNr8O22UIMrqYbchJQJnos4eooYzYJA==",
"path": "system.reflection.typeextensions/4.3.0",
"hashPath": "system.reflection.typeextensions.4.3.0.nupkg.sha512"
},
"System.Resources.ResourceManager/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-/zrcPkkWdZmI4F92gL/TPumP98AVDu/Wxr3CSJGQQ+XN6wbRZcyfSKVoPo17ilb3iOr0cCRqJInGwNMolqhS8A==",
"path": "system.resources.resourcemanager/4.3.0",
"hashPath": "system.resources.resourcemanager.4.3.0.nupkg.sha512"
},
"System.Runtime/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-JufQi0vPQ0xGnAczR13AUFglDyVYt4Kqnz1AZaiKZ5+GICq0/1MH/mO/eAJHt/mHW1zjKBJd7kV26SrxddAhiw==",
"path": "system.runtime/4.3.0",
"hashPath": "system.runtime.4.3.0.nupkg.sha512"
},
"System.Runtime.Extensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-guW0uK0fn5fcJJ1tJVXYd7/1h5F+pea1r7FLSOz/f8vPEqbR2ZAknuRDvTQ8PzAilDveOxNjSfr0CHfIQfFk8g==",
"path": "system.runtime.extensions/4.3.0",
"hashPath": "system.runtime.extensions.4.3.0.nupkg.sha512"
},
"System.Runtime.Handles/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-OKiSUN7DmTWeYb3l51A7EYaeNMnvxwE249YtZz7yooT4gOZhmTjIn48KgSsw2k2lYdLgTKNJw/ZIfSElwDRVgg==",
"path": "system.runtime.handles/4.3.0",
"hashPath": "system.runtime.handles.4.3.0.nupkg.sha512"
},
"System.Runtime.InteropServices/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-uv1ynXqiMK8mp1GM3jDqPCFN66eJ5w5XNomaK2XD+TuCroNTLFGeZ+WCmBMcBDyTFKou3P6cR6J/QsaqDp7fGQ==",
"path": "system.runtime.interopservices/4.3.0",
"hashPath": "system.runtime.interopservices.4.3.0.nupkg.sha512"
},
"System.Runtime.Serialization.Json/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-CpVfOH0M/uZ5PH+M9+Gu56K0j9lJw3M+PKRegTkcrY/stOIvRUeonggxNrfBYLA5WOHL2j15KNJuTuld3x4o9w==",
"path": "system.runtime.serialization.json/4.3.0",
"hashPath": "system.runtime.serialization.json.4.3.0.nupkg.sha512"
},
"System.Runtime.Serialization.Primitives/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-Wz+0KOukJGAlXjtKr+5Xpuxf8+c8739RI1C+A2BoQZT+wMCCoMDDdO8/4IRHfaVINqL78GO8dW8G2lW/e45Mcw==",
"path": "system.runtime.serialization.primitives/4.3.0",
"hashPath": "system.runtime.serialization.primitives.4.3.0.nupkg.sha512"
},
"System.Text.Encoding/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-BiIg+KWaSDOITze6jGQynxg64naAPtqGHBwDrLaCtixsa5bKiR8dpPOHA7ge3C0JJQizJE+sfkz1wV+BAKAYZw==",
"path": "system.text.encoding/4.3.0",
"hashPath": "system.text.encoding.4.3.0.nupkg.sha512"
},
"System.Text.Encoding.Extensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-YVMK0Bt/A43RmwizJoZ22ei2nmrhobgeiYwFzC4YAN+nue8RF6djXDMog0UCn+brerQoYVyaS+ghy9P/MUVcmw==",
"path": "system.text.encoding.extensions/4.3.0",
"hashPath": "system.text.encoding.extensions.4.3.0.nupkg.sha512"
},
"System.Text.RegularExpressions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-RpT2DA+L660cBt1FssIE9CAGpLFdFPuheB7pLpKpn6ZXNby7jDERe8Ua/Ne2xGiwLVG2JOqziiaVCGDon5sKFA==",
"path": "system.text.regularexpressions/4.3.0",
"hashPath": "system.text.regularexpressions.4.3.0.nupkg.sha512"
},
"System.Threading/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-VkUS0kOBcUf3Wwm0TSbrevDDZ6BlM+b/HRiapRFWjM5O0NS0LviG0glKmFK+hhPDd1XFeSdU1GmlLhb2CoVpIw==",
"path": "system.threading/4.3.0",
"hashPath": "system.threading.4.3.0.nupkg.sha512"
},
"System.Threading.Tasks/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-LbSxKEdOUhVe8BezB/9uOGGppt+nZf6e1VFyw6v3DN6lqitm0OSn2uXMOdtP0M3W4iMcqcivm2J6UgqiwwnXiA==",
"path": "system.threading.tasks/4.3.0",
"hashPath": "system.threading.tasks.4.3.0.nupkg.sha512"
},
"System.Threading.Tasks.Extensions/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-npvJkVKl5rKXrtl1Kkm6OhOUaYGEiF9wFbppFRWSMoApKzt2PiPHT2Bb8a5sAWxprvdOAtvaARS9QYMznEUtug==",
"path": "system.threading.tasks.extensions/4.3.0",
"hashPath": "system.threading.tasks.extensions.4.3.0.nupkg.sha512"
},
"System.Xml.ReaderWriter/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-GrprA+Z0RUXaR4N7/eW71j1rgMnEnEVlgii49GZyAjTH7uliMnrOU3HNFBr6fEDBCJCIdlVNq9hHbaDR621XBA==",
"path": "system.xml.readerwriter/4.3.0",
"hashPath": "system.xml.readerwriter.4.3.0.nupkg.sha512"
},
"System.Xml.XDocument/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-5zJ0XDxAIg8iy+t4aMnQAu0MqVbqyvfoUVl1yDV61xdo3Vth45oA2FoY4pPkxYAH5f8ixpmTqXeEIya95x0aCQ==",
"path": "system.xml.xdocument/4.3.0",
"hashPath": "system.xml.xdocument.4.3.0.nupkg.sha512"
},
"System.Xml.XmlDocument/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-lJ8AxvkX7GQxpC6GFCeBj8ThYVyQczx2+f/cWHJU8tjS7YfI6Cv6bon70jVEgs2CiFbmmM8b9j1oZVx0dSI2Ww==",
"path": "system.xml.xmldocument/4.3.0",
"hashPath": "system.xml.xmldocument.4.3.0.nupkg.sha512"
},
"System.Xml.XmlSerializer/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-MYoTCP7EZ98RrANESW05J5ZwskKDoN0AuZ06ZflnowE50LTpbR5yRg3tHckTVm5j/m47stuGgCrCHWePyHS70Q==",
"path": "system.xml.xmlserializer/4.3.0",
"hashPath": "system.xml.xmlserializer.4.3.0.nupkg.sha512"
}
}
}
Binary file not shown.
@@ -0,0 +1,9 @@
{
"runtimeOptions": {
"tfm": "netcoreapp2.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "2.0.0"
}
}
}
+1
View File
@@ -0,0 +1 @@
dotnet AshamaneDependencyManager.dll
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
name=$1
branch=$2
database=$3
echo "Database Updater check script:"
echo " Checking database '${name}' for missing filenames in tables..."
echo
# Select all entries which are in the updates table
entries=$(mysql -uroot ${database} -e "SELECT name FROM updates" | grep ".sql")
cd sql/ashamane/${name}
error=0
updates=0
for file in *.sql
do
# Check if the given update is in the `updates` table.
if echo "${entries}" | grep -q "^${file}"; then
# File is ok
updates=$((updates+1))
else
# The update isn't listed in the updates table of the given database.
echo "- \"sql/updates/${name}/${file}\" is missing in the '${name}'.'updates' table."
error=1
fi
done
if [ ${error} -ne 0 ]
then
echo
echo "Fatal error:"
echo " The Database Updater is broken for the '${name}' database,"
echo " because the applied update is missing in the '${name}'.'updates' table."
echo
echo "How to fix:"
echo " Insert the missing names of the already applied sql updates"
echo " to the 'updates' table of the '${name}' base dump ('sql/base/${name}_database.sql')."
exit 1
else
echo " Everything is OK, finished checking ${updates} updates."
exit 0
fi
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
perl -wpi -e "s/\t/ /g" $1
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
perl -wpi -e "s/ +$//g" $1
+13
View File
@@ -0,0 +1,13 @@
==== PHP merger (index.php + merge.php) ====
This is a PHP script for merging a new .dist file with your existing .conf file (worldserver.conf.dist and bnetserver.conf.dist)
It should also work with mangos dist/conf files as well.
It uses sessions so it is multi user safe, it adds any options that are removed to the bottom of the file,
commented out, just in case it removes something it shouldn't,
and, if you add all of your custom patch configs below "# Custom" they will be copied exactly as they are.
==== Perl merger (tc-conf-merger.pl) ====
Perl based command line merger script. This script feeds a .conf.dist file with variables that exist in an old .conf file,
comments and custom options are ignored.
+169
View File
@@ -0,0 +1,169 @@
<!--
@title Configuration file merger/differ.
@about This script allows you to diff two config files and select which value to pick between the two.
It will then give you an updated configuration file with the settings you chose.
How-to: a) Paste both versions of your config file, submit the form.
b) Select values you want to keep in the next form, then submit said form.
c) Copy the output'd config file and profit!
Note: if either one of your config file has custom values, make sure that it is set to be the NEW
config file on the first step (right hand textarea). This will be adressed at a later date.
@author Warpten
@date 05/17/2014
@license GNU GPL v2(GPL)
@version 0.0.1
-->
<!DOCTYPE html>
<html>
<head>
<title>&lt;world/auth&gt;server.conf diff</title>
<style type="text/css">
form * { font-family: Verdana; font-size: 11px; }
form#step1 { position: relative; width: 800px; }
form#step2 { width: 500px; }
form > div { position: absolute; width: 50%; height: 500px; }
form > div:nth-child(1) { right: 0px; }
textarea { width: 90%; height: 500px; }
h3 { display: block; margin: 3px; padding: auto; text-align: center; }
input.valueName { border: 0px; background-color: white; }
form > p { margin: 0; padding: 3px; border-bottom: 1px solid black; }
textarea#result { width: 1000px; }
</style>
</head>
<body>
<?php
function printIndent($string, $indent = 1)
{
echo str_pad("\r\n" . $string, $indent, " ");
}
if (!isset($_POST['step']))
{
?>
<form action="" method="POST" id="step1">
<div>
<h3>Paste the new configuration file</h3>
<textarea name="leftFile"></textarea>
</div><div>
<h3>Paste the old configuration file</h3>
<textarea name="rightFile"></textarea>
<input type="submit" value="Compare files" />
</div>
<input type="hidden" name="step" value="0" />
</form>
<?php
}
else if ($_POST['step'] == 0)
{
if (@empty($_POST['leftFile']) || @empty($_POST['rightFile']))
printf("You did not provide either the old or the new configuration file.<br />");
define('EOL', "\n\n");
$settingsData = array();
// Process them
$newFile = explode(EOL, $_POST['leftFile']);
$oldFile = explode(EOL, $_POST['rightFile']);
for ($i = 0, $o = count($oldFile); $i < $o; ++$i)
{
$oldFile[$i] = explode(PHP_EOL, $oldFile[$i]);
for ($j = 0, $p = count($oldFile[$i]); $j < $p; ++$j)
{
$currentLine = $oldFile[$i][$j];
if (preg_match("#^([A-Z.]+) = (?:\"?)(.*)(?:\"?)$#iU", $currentLine, $data) !== false)
if (strlen($data[1]) != 0)
$settingsData[$data[1]]["oldValue"] = str_replace('"', '', trim($data[2]));
}
}
for ($i = 0, $o = count($newFile); $i < $o; ++$i)
{
$newFile[$i] = explode(PHP_EOL, $newFile[$i]);
for ($j = 0, $p = count($newFile[$i]); $j < $p; ++$j)
{
$currentLine = $newFile[$i][$j];
if (preg_match("#^([A-Z.]+) = (?:\"?)(.*)(?:\"?)$#iU", $currentLine, $data) !== false)
if (strlen($data[1]) != 0)
$settingsData[$data[1]]["newValue"] = str_replace('"', '', trim($data[2]));
}
}
printIndent("<p>Please select values you want to keep. Note the script will default to new values, unless said <i>new</i> value does not exist.<br />You also can take advantage of this form and edit fields.</p>", 1);
printIndent('<form action="" method="POST" id="step2">', 1);
foreach ($settingsData as $itemName => &$values)
{
$displayOld = isset($values['oldValue']) ? $values['oldValue'] : "Value missing";
$displayNew = isset($values['newValue']) ? $values['newValue'] : "Value missing";
if ($displayOld == $displayNew)
continue;
$line = '<p><input type="text" class="valueName" name="nameCross[]" value="' . $itemName . '" />';
$line .= '<input type="radio" name="optionSelector[' . $itemName . ']" value="oldValue" ' . ($displayOld != "Value missing" ? "checked" : "") . '/>';
$line .= '<input type="text" name="oldValue[]" value="' . $displayOld . '" /> ';
$line .= '<input type="radio" name="optionSelector[' . $itemName . ']" value="newValue" ' . ($displayNew != "Value missing" ? "checked" : "") . '/>';
$line .= '<input type="text" name="newValue[]" value="' . $displayNew . '" /></p>';
printIndent($line, 2);
}
printIndent('<input type="hidden" name="step" value="1" />', 2);
printIndent('<input type="submit" value="Gief resulting configuration file" />', 2);
printIndent('<input type="hidden" name="file" value="' . htmlspecialchars($_POST['rightFile']) . '" />', 2);
printIndent('</form>', 1);
}
else if ($_POST['step'] == 1)
{
$errors = array();
$confFile = $_POST['file'];
foreach ($_POST['optionSelector'] as $valueName => &$keyName)
{
$definiteValueIndex = -1;
foreach ($_POST['nameCross'] as $index => &$key)
{
if ($key == $valueName)
{
$definiteValueIndex = $index;
break;
}
}
if ($definiteValueIndex == -1)
{
// TODO: Handle custom values that get lost
continue;
}
$newStr = $_POST[$keyName][$definiteValueIndex];
$oldStr = $_POST[$keyName == "oldValue" ? "newValue" : "oldValue"][$definiteValueIndex];
if (!ctype_digit($newStr))
$newStr = '"' . $newStr . '"';
if (!ctype_digit($oldStr))
$oldStr = '"' . $oldStr . '"';
$newValueString = $valueName . " = " . $newStr;
$oldValueString = $valueName . " = " . $oldStr;
$confFile = str_replace($oldValueString, $newValueString, $confFile);
}
echo "<p>Here is your new configuration file:</p>";
echo '<form><textarea id="result">';
printf('%s', $confFile);
echo '</textarea></form>';
if (!empty($errors))
{
echo "<p>The following errors happened during processing:</p><ul><li>";
echo implode("</li><li>", $errors);
echo "</li>";
}
}
?>
<script type="text/javascript">
</script>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
<?php
/*
* Project Name: Config File Merge For Mangos/Trinity Server
* Date: 01.01.2010 inital version (0.0.1a)
* Author: Paradox
* Copyright: Paradox
* Email: iamparadox@netscape.net (paypal email)
* License: GNU General Public License v2(GPL)
*/
?>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<FORM enctype="multipart/form-data" ACTION="merge.php" METHOD="POST">
Dist File
<br />
<INPUT name="File1" TYPE="file">
<br />
Current Conf File
<br />
<INPUT name="File2" TYPE="file">
<br />
<INPUT TYPE=RADIO NAME="eol" VALUE="0" CHECKED >Win32 -
<INPUT TYPE=RADIO NAME="eol" VALUE="1" >UNIX/Linux
<br />
<INPUT TYPE="submit" VALUE="Submit">
<br />
If you have any custom settings, such as from patches,
<br />
make sure they are at the bottom of the file following
<br />
this block (add it if it's not there)
<br />
###############################################################################
<br />
# Custom
<br />
###############################################################################
<br />
<br />
</FORM>
+159
View File
@@ -0,0 +1,159 @@
<?php
/*
* Project Name: Config File Merge For Mangos/Trinity Server
* Date: 01.01.2010 inital version (0.0.1a)
* Author: Paradox
* Copyright: Paradox
* Email: iamparadox@netscape.net (paypal email)
* License: GNU General Public License v2(GPL)
*/
if (!empty($_FILES['File1']) && !empty($_FILES['File2']))
{
session_id();
session_start();
$basedir = "merge";
$eol = "\r\n";
if ($_POST['eol'])
$eol = "\n";
else
$eol = "\r\n";
if (!file_exists($basedir))
mkdir($basedir);
if (!file_exists($basedir."/".session_id()))
mkdir($basedir."/".session_id());
$upload1 = $basedir."/".session_id()."/".basename($_FILES['File1']['name']);
$upload2 = $basedir."/".session_id()."/".basename($_FILES['File2']['name']);
$newconfig = $basedir."/".session_id()."/trinitycore.conf.merged";
$out_file = fopen($newconfig, w);
$success = false;
if (move_uploaded_file($_FILES['File1']['tmp_name'], $upload1))
{
$success = true;
}
else
{
$success = false;
}
if (move_uploaded_file($_FILES['File2']['tmp_name'], $upload2))
{
$success = true;
}
else
{
$success = false;
}
if ($success)
{
$custom_found = false;
$in_file1 = fopen($upload1,r);
$in_file2 = fopen($upload2,r);
$array1 = array();
$array2 = array();
$line = trim(fgets($in_file1));
while (!feof($in_file1))
{
if ((substr($line,0,1) != '#' && substr($line,0,1) != ''))
{
list($key, $val) = explode("=",$line);
$key = trim($key);
$val = trim($val);
$array1[$key] = $val;
}
$line = trim(fgets($in_file1));
}
$line = trim(fgets($in_file2));
while (!feof($in_file2) && !$custom_found)
{
if (substr($line,0,1) != '#' && substr($line,0,1) != '')
{
list($key, $val) = explode("=",$line);
$key = trim($key);
$val = trim($val);
$array2[$key] = $val;
}
if (strtolower($line) == "# custom")
$custom_found = true;
else
$line = trim(fgets($in_file2));
}
fclose($in_file1);
foreach($array2 as $k => $v)
{
if (array_key_exists($k, $array1))
{
$array1[$k] = $v;
unset($array2[$k]);
}
}
$in_file1 = fopen($upload1,r);
$line = trim(fgets($in_file1));
while (!feof($in_file1))
{
if (substr($line,0,1) != '#' && substr($line,0,1) != '')
{
$array = array();
while (substr($line,0,1) != '#' && substr($line,0,1) != '')
{
list($key, $val) = explode("=",$line);
$key = trim($key);
$val = trim($val);
$array[$key] = $val;
$line = trim(fgets($in_file1));
}
foreach($array as $k => $v)
{
if (array_key_exists($k, $array1))
fwrite($out_file, $k."=".$array1[$k].$eol);
else
continue;
}
unset($array);
if (!feof($in_file1))
fwrite($out_file, $line.$eol);
}
else
fwrite($out_file, $line.$eol);
$line = trim(fgets($in_file1));
}
if ($custom_found)
{
fwrite($out_file, $eol);
fwrite($out_file, "###############################################################################".$eol);
fwrite($out_file, "# Custom".$eol);
$line = trim(fgets($in_file2));
while (!feof($in_file2))
{
fwrite($out_file, $line.$eol);
$line = trim(fgets($in_file2));
}
}
$first = true;
foreach($array2 as $k => $v)
{
if ($first)
{
fwrite($out_file, $eol);
fwrite($out_file, "###############################################################################".$eol);
fwrite($out_file, "# The Following values were removed from the config.".$eol);
$first = false;
}
fwrite($out_file, "# ".$k."=".$v.$eol);
}
unset($array1);
unset($array2);
fclose($in_file1);
fclose($in_file2);
fclose($out_file);
unlink($upload1);
unlink($upload2);
echo "Process done";
echo "<br /><a href=".$newconfig.">Click here to retrieve your merged conf</a>";
}
}
else
{
echo "An error has occurred";
}
?>
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/perl -w
# Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
# Author: leak
# Date: 2010-12-06
# Note: Based on conf file format of rev 10507
use strict;
if (@ARGV != 3)
{
print("Usage:\ntc-conf-merger.pl <path to new .conf.dist> <path to old .conf> <path to output .conf>\n");
exit(1);
}
if (! -e $ARGV[0])
{
print("No file found at: ".$ARGV[0]);
exit(1);
}
elsif (! -e $ARGV[1])
{
print("No file found at: ".$ARGV[1]);
exit(1);
}
open CONFDIST, "<", $ARGV[0] or die "Error: Could not open ".$ARGV[0]."\n";
my $confdist = join "", <CONFDIST>;
close CONFDIST;
open CONFOLD, "<", $ARGV[1] or die "Error: Could not open ".$ARGV[1]."\n";
my $confold = join "", <CONFOLD>;
close CONFOLD;
while ($confold =~ m/^(?!#)(.*?)\s+?=\s+?(.*?)$/mg) {
my $key = $1, my $value = $2;
$confdist =~ s/^(\Q$key\E)(\s+?=\s+?)(.*)/$1$2$value/mg;
}
open OUTPUT, ">", $ARGV[2] or die "Error: Could not open ".$ARGV[2]."\n";
binmode(OUTPUT);
print OUTPUT $confdist;
close OUTPUT;
+13
View File
@@ -0,0 +1,13 @@
The included crashreport.gdb allows for semiautomated hunting of
crashes. The crashlog-file will be named backtrace.log and contains all
the commands required to partially automate a crashlog-creation with the
proper information.
Usage: gdb -x crashreport.gdb <executable file>
For creating an efficient backtrace, use -DCMAKE_BUILD_TYPE=Debug as a
parameter to CMake during configuration - this increases the filesize,
but includes all the needed information for a decent and efficient
crashreport.
-- Good luck, and happy crashhunting.
+18
View File
@@ -0,0 +1,18 @@
set logging overwrite on
set logging file backtrace.log
handle SIG33 pass nostop noprint
set pagination 0
set logging on
echo \n--- DEBUG: --- START\n\n
run
echo \n--- DEBUG: BACKTRACE FULL\n\n
backtrace full
echo \n--- DEBUG: INFO REGISTERS\n\n
info registers
echo \n--- DEBUG: CALLS (x/32i $pc)\n\n
x/32i $pc
echo \n--- DEBUG: THREAD APPLY ALL BACKTRACE\n
thread apply all backtrace
echo \n--- DEBUG: --- STOP\n\n
set logging off
quit
+57
View File
@@ -0,0 +1,57 @@
@ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO Trinitycore dbc/db2, maps, vmaps, mmaps extractor
ECHO ...............................................
ECHO PRESS 1, 2, 3 OR 4 to select your task, or 5 to EXIT.
ECHO ...............................................
ECHO.
ECHO The vmaps extractor output text below is intended and not an error:
ECHO ..........................................
ECHO Extracting World\Wmo\Band\Final_Stage.wmo
ECHO No such file.
ECHO Couldn't open RootWmo!!!
ECHO Done!
ECHO ..........................................
ECHO.
ECHO 1 - Extract dbc/db2 and maps
ECHO 2 - Extract vmaps (needs maps to be extracted before you run this)
ECHO 3 - Extract mmaps (needs vmaps to be extracted before you run this, may take hours)
ECHO 4 - Extract all (may take hours)
ECHO 5 - EXIT
ECHO.
SET /P M=Type 1, 2, 3, 4 or 5 then press ENTER:
IF %M%==1 GOTO MAPS
IF %M%==2 GOTO VMAPS
IF %M%==3 GOTO MMAPS
IF %M%==4 GOTO ALL
IF %M%==5 GOTO :EOF
:MAPS
start /b /w mapextractor.exe
GOTO MENU
:VMAPS
start /b /w vmap4extractor.exe
start /b /w vmap4assembler.exe Buildings vmaps
rmdir Buildings /s /q
GOTO MENU
:MMAPS
ECHO This may take a few hours to complete. Please be patient.
PAUSE
start /b /w mmaps_generator.exe
GOTO MENU
:ALL
ECHO This may take a few hours to complete. Please be patient.
PAUSE
start /b /w mapextractor.exe
start /b /w vmap4extractor.exe
start /b /w vmap4assembler.exe
rmdir Buildings /s /q
start /b /w mmaps_generator.exe
GOTO MENU
+889
View File
@@ -0,0 +1,889 @@
{
"id": 1,
"title": "General info",
"originalTitle": "General info",
"tags": [],
"style": "dark",
"timezone": "browser",
"editable": true,
"hideControls": false,
"sharedCrosshair": false,
"rows": [
{
"collapse": false,
"editable": true,
"height": "25px",
"panels": [
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "Influx",
"editable": true,
"error": false,
"format": "none",
"id": 5,
"interval": null,
"isNew": true,
"links": [],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"span": 3,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"targets": [
{
"dsType": "influxdb",
"groupBy": [
{
"params": [
"auto"
],
"type": "time"
}
],
"measurement": "online_players",
"policy": "default",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"type": "field",
"params": [
"value"
]
},
{
"type": "last",
"params": []
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/^$realm$/"
}
]
}
],
"thresholds": "",
"title": "Online players",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current",
"timeFrom": null,
"timeShift": null,
"hideTimeOverride": false
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "Influx",
"editable": true,
"error": false,
"format": "none",
"id": 6,
"interval": null,
"isNew": true,
"links": [],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"span": 3,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"targets": [
{
"dsType": "influxdb",
"groupBy": [
{
"params": [
"auto"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "update_time_diff",
"policy": "default",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/^$realm$/"
}
]
}
],
"thresholds": "",
"title": "Update diff (avg)",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg",
"timeFrom": "1m"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "Influx",
"editable": true,
"error": false,
"format": "none",
"id": 7,
"interval": null,
"isNew": true,
"links": [],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"span": 3,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"targets": [
{
"dsType": "influxdb",
"groupBy": [
{
"params": [
"auto"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "update_time_diff",
"policy": "default",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
}
],
"thresholds": "",
"title": "Update diff (avg)",
"transparent": false,
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg",
"timeFrom": "5m"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "Influx",
"editable": true,
"error": false,
"format": "none",
"id": 8,
"interval": null,
"isNew": true,
"links": [],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"span": 3,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"targets": [
{
"dsType": "influxdb",
"groupBy": [
{
"params": [
"auto"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "update_time_diff",
"policy": "default",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/^$realm$/"
}
]
}
],
"thresholds": "",
"title": "Update diff (avg)",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg",
"timeFrom": "15m",
"timeShift": null
}
],
"title": "New row"
},
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 1,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Update diff",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "update_time_diff",
"policy": "default",
"query": "SELECT mean(\"value\") FROM \"update_time_diff\" WHERE \"realm\" =~ /$realm$/ AND $timeFilter GROUP BY time($interval) fill(null)",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/$realm$/"
}
]
}
],
"timeFrom": null,
"timeShift": null,
"title": "Update diff",
"tooltip": {
"msResolution": false,
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"xaxis": {
"show": true
},
"y-axis": true,
"y_formats": [
"ms",
"short"
],
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"title": "Row"
},
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 4,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Online players",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "online_players",
"policy": "default",
"query": "SELECT mean(\"value\") FROM \"online_players\" WHERE \"realm\" =~ /$realm$/ AND $timeFilter GROUP BY time($interval) fill(null)",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/$realm$/"
}
]
}
],
"timeFrom": null,
"timeShift": null,
"title": "Online players",
"tooltip": {
"msResolution": false,
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"xaxis": {
"show": true
},
"y-axis": true,
"y_formats": [
"short",
"short"
],
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"title": "New row"
},
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 3,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "Logouts",
"transform": "negative-Y"
}
],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Logins",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"measurement": "player_events",
"policy": "default",
"query": "SELECT count(\"text\") FROM \"player_events\" WHERE \"realm\" =~ /$realm$/ AND \"title\" = 'Login' AND $timeFilter GROUP BY time($interval) fill(0)",
"rawQuery": true,
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"text"
],
"type": "field"
},
{
"params": [],
"type": "count"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=",
"value": "Trinity"
}
]
},
{
"alias": "Logouts",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"policy": "default",
"query": "SELECT count(\"text\") FROM \"player_events\" WHERE \"realm\" =~ /$realm$/ AND \"title\" = 'Logout' AND $timeFilter GROUP BY time($interval) fill(0)",
"rawQuery": true,
"refId": "B",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
}
],
"timeFrom": null,
"timeShift": null,
"title": "Player login/logout",
"tooltip": {
"msResolution": false,
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"xaxis": {
"show": true
},
"y-axis": true,
"y_formats": [
"short",
"short"
],
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"title": "New row"
}
],
"time": {
"from": "now-15m",
"to": "now"
},
"timepicker": {
"now": true,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"templating": {
"list": [
{
"allFormat": "regex values",
"current": {
"text": "Trinity",
"value": "Trinity"
},
"datasource": "Influx",
"includeAll": false,
"multi": false,
"multiFormat": "regex values",
"name": "realm",
"options": [
{
"text": "Trinity",
"value": "Trinity",
"selected": true
}
],
"query": "show tag values from events with key = realm",
"refresh": 1,
"regex": "",
"type": "query"
}
]
},
"annotations": {
"list": [
{
"datasource": "Influx",
"enable": true,
"iconColor": "#C0C6BE",
"iconSize": 13,
"lineColor": "rgba(255, 96, 96, 0.592157)",
"name": "Global Events",
"query": "select title, text from events where $timeFilter and realm =~ /$realm$/",
"showLine": true,
"textColumn": "text",
"titleColumn": "title"
}
]
},
"refresh": "1m",
"schemaVersion": 12,
"version": 7,
"links": []
}
+339
View File
@@ -0,0 +1,339 @@
{
"id": 2,
"title": "Maps, vmaps and mmaps",
"originalTitle": "Maps, vmaps and mmaps",
"tags": [],
"style": "dark",
"timezone": "browser",
"editable": true,
"hideControls": false,
"sharedCrosshair": false,
"rows": [
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 2,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "Unload tile",
"transform": "negative-Y"
}
],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Load tile",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"0"
],
"type": "fill"
}
],
"query": "SELECT count(\"title\") FROM \"map_events\" WHERE \"realm\" =~ /$realm$/ AND \"title\" = 'LoadMapTile' AND $timeFilter GROUP BY time($interval) fill(0)",
"rawQuery": true,
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
},
{
"alias": "Unload tile",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"query": "SELECT count(\"title\") FROM \"map_events\" WHERE \"realm\" =~ /$realm$/ AND \"title\" = 'UnloadMapTile' AND $timeFilter GROUP BY time($interval) fill(0)",
"rawQuery": true,
"refId": "B",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
}
],
"timeFrom": null,
"timeShift": null,
"title": "Map",
"tooltip": {
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"y-axis": true,
"y_formats": [
"short",
"short"
]
}
],
"title": "Row"
},
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 1,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Pathfinding queries",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"query": "SELECT count(\"title\") FROM \"mmap_events\" WHERE \"realm\" =~ /$realm$/ AND \"title\" = 'CalculatePath' AND $timeFilter GROUP BY time($interval) fill(0)",
"rawQuery": true,
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
}
],
"timeFrom": null,
"timeShift": null,
"title": "MMap",
"tooltip": {
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"y-axis": true,
"y_formats": [
"short",
"short"
]
}
],
"title": "New row"
}
],
"time": {
"from": "now-15m",
"to": "now"
},
"timepicker": {
"now": true,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"templating": {
"list": [
{
"allFormat": "regex values",
"current": {
"text": "Trinity",
"value": "Trinity"
},
"datasource": "Influx",
"includeAll": false,
"multi": false,
"multiFormat": "regex values",
"name": "realm",
"options": [
{
"text": "Trinity",
"value": "Trinity",
"selected": true
}
],
"query": "show tag values from events with key = realm",
"refresh": true,
"type": "query"
}
]
},
"annotations": {
"list": [
{
"datasource": "Influx",
"enable": true,
"iconColor": "#C0C6BE",
"iconSize": 13,
"lineColor": "rgba(255, 96, 96, 0.592157)",
"name": "Global Events",
"query": "select title, text from events where $timeFilter and realm =~ /$realm$/",
"showLine": true,
"textColumn": "text",
"titleColumn": "title"
}
]
},
"refresh": "1m",
"schemaVersion": 8,
"version": 11,
"links": []
}
+242
View File
@@ -0,0 +1,242 @@
{
"id": 3,
"title": "Network",
"originalTitle": "Network",
"tags": [],
"style": "dark",
"timezone": "browser",
"editable": true,
"hideControls": false,
"sharedCrosshair": false,
"rows": [
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"datasource": "Influx",
"editable": true,
"error": false,
"fill": 1,
"grid": {
"leftLogBase": 1,
"leftMax": null,
"leftMin": null,
"rightLogBase": 1,
"rightMax": null,
"rightMin": null,
"threshold1": null,
"threshold1Color": "rgba(216, 200, 27, 0.27)",
"threshold2": null,
"threshold2Color": "rgba(234, 112, 112, 0.22)"
},
"id": 1,
"isNew": true,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"span": 12,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "Processed packets",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"0"
],
"type": "fill"
}
],
"measurement": "processed_packets",
"query": "SELECT sum(\"value\") FROM \"processed_packets\" WHERE \"realm\" =~ /$realm$/ AND $timeFilter GROUP BY time($interval) fill(0)",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "sum"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/$realm$/"
}
]
},
{
"alias": "Processed packets / mean per session",
"dsType": "influxdb",
"groupBy": [
{
"params": [
"$interval"
],
"type": "time"
},
{
"params": [
"0"
],
"type": "fill"
}
],
"measurement": "processed_packets",
"query": "SELECT mean(\"value\") FROM \"processed_packets\" WHERE \"realm\" =~ /$realm$/ AND $timeFilter GROUP BY time($interval) fill(0)",
"refId": "B",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": [
{
"key": "realm",
"operator": "=~",
"value": "/$realm$/"
}
]
}
],
"timeFrom": null,
"timeShift": null,
"title": "Processed packets",
"tooltip": {
"shared": true,
"value_type": "cumulative"
},
"type": "graph",
"x-axis": true,
"y-axis": true,
"y_formats": [
"short",
"short"
]
}
],
"title": "Row"
}
],
"time": {
"from": "now-15m",
"to": "now"
},
"timepicker": {
"now": true,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"templating": {
"list": [
{
"allFormat": "regex values",
"current": {
"text": "Trinity",
"value": "Trinity"
},
"datasource": "Influx",
"includeAll": false,
"multi": false,
"multiFormat": "regex values",
"name": "realm",
"options": [
{
"text": "Trinity",
"value": "Trinity",
"selected": true
}
],
"query": "show tag values from events with key = realm",
"refresh": true,
"type": "query"
}
]
},
"annotations": {
"list": [
{
"datasource": "Influx",
"enable": true,
"iconColor": "#C0C6BE",
"iconSize": 13,
"lineColor": "rgba(255, 96, 96, 0.592157)",
"name": "Global Events",
"query": "select title, text from events where $timeFilter and realm =~ /$realm$/",
"showLine": true,
"textColumn": "text",
"titleColumn": "title"
}
]
},
"refresh": "1m",
"schemaVersion": 8,
"version": 7,
"links": []
}
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
cat ../sql/updates/world/master/*.sql > world_update.sql
cat ../sql/updates/hotfixes/master/*.sql > hotfixes_update.sql
+2
View File
@@ -0,0 +1,2 @@
copy /a ..\sql\updates\world\master\*.sql /b world_updates.sql
copy /a ..\sql\updates\hotfixes\master\*.sql /b hotfixes_updates.sql
+68
View File
@@ -0,0 +1,68 @@
//
// Created by tea on 10.03.16.
//
#include <vector>
#include "BnetFileGenerator.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include "BnetCodeGenerator.h"
bool BnetCodeGenerator::Generate(pb::FileDescriptor const* file, std::string const& parameter,
pbc::GeneratorContext* generator_context, std::string* error) const
{
std::vector<std::pair<std::string, std::string>> options;
google::protobuf::compiler::ParseGeneratorParameter(parameter, &options);
// -----------------------------------------------------------------
// parse generator options
google::protobuf::compiler::cpp::Options file_options;
for (int i = 0; i < options.size(); i++)
{
if (options[i].first == "dllexport_decl")
{
file_options.dllexport_decl = options[i].second;
}
else if (options[i].first == "safe_boundary_check")
{
file_options.safe_boundary_check = true;
}
else
{
*error = "Unknown generator option: " + options[i].first;
return false;
}
}
// -----------------------------------------------------------------
std::string basename = google::protobuf::compiler::cpp::StripProto(file->name());
basename.append(".pb");
BnetFileGenerator file_generator(file, file_options);
// Generate header.
{
pb::scoped_ptr <google::protobuf::io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".h"));
google::protobuf::io::Printer printer(output.get(), '$');
file_generator.GenerateHeader(&printer);
}
// Generate cc file.
{
pb::scoped_ptr <google::protobuf::io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".cc"));
google::protobuf::io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
}
return true;
}
+24
View File
@@ -0,0 +1,24 @@
//
// Created by tea on 10.03.16.
//
#ifndef PROTOC_BNET_BNETCODEGENERATOR_H
#define PROTOC_BNET_BNETCODEGENERATOR_H
#include <google/protobuf/compiler/code_generator.h>
#include <string>
namespace pb = google::protobuf;
namespace pbc = pb::compiler;
class BnetCodeGenerator : public pbc::CodeGenerator
{
public:
bool Generate(pb::FileDescriptor const* file,
std::string const& parameter,
pbc::GeneratorContext* generator_context,
std::string* error) const override;
};
#endif //PROTOC_BNET_BNETCODEGENERATOR_H
+698
View File
@@ -0,0 +1,698 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "BnetFileGenerator.h"
#include <memory>
#include <set>
#include "google/protobuf/compiler/cpp/cpp_enum.h"
#include "BnetServiceGenerator.h"
#include "BnetCodeGenerator.h"
#include "google/protobuf/compiler/cpp/cpp_extension.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include "google/protobuf/compiler/cpp/cpp_message.h"
#include "google/protobuf/compiler/cpp/cpp_field.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include "google/protobuf/stubs/strutil.h"
// ===================================================================
BnetFileGenerator::BnetFileGenerator(const pb::FileDescriptor* file, const pbcpp::Options& options)
: file_(file),
message_generators_(
new pb::scoped_ptr<pbcpp::MessageGenerator>[file->message_type_count()]),
enum_generators_(
new pb::scoped_ptr<pbcpp::EnumGenerator>[file->enum_type_count()]),
service_generators_(
new pb::scoped_ptr<BnetServiceGenerator>[file->service_count()]),
extension_generators_(
new pb::scoped_ptr<pbcpp::ExtensionGenerator>[file->extension_count()]),
options_(options)
{
for (int i = 0; i < file->message_type_count(); i++)
{
message_generators_[i].reset(
new pbcpp::MessageGenerator(file->message_type(i), options));
}
for (int i = 0; i < file->enum_type_count(); i++)
{
enum_generators_[i].reset(
new pbcpp::EnumGenerator(file->enum_type(i), options));
}
for (int i = 0; i < file->service_count(); i++)
{
service_generators_[i].reset(
new BnetServiceGenerator(file->service(i), options));
}
for (int i = 0; i < file->extension_count(); i++)
{
extension_generators_[i].reset(
new pbcpp::ExtensionGenerator(file->extension(i), options));
}
pb::SplitStringUsing(file_->package(), ".", &package_parts_);
}
BnetFileGenerator::~BnetFileGenerator() { }
void BnetFileGenerator::GenerateHeader(pb::io::Printer* printer)
{
std::string filename_identifier = pbcpp::FilenameIdentifier(file_->name());
// Generate top of header.
printer->Print(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
"#ifndef PROTOBUF_$filename_identifier$__INCLUDED\n"
"#define PROTOBUF_$filename_identifier$__INCLUDED\n"
"\n"
"#include <string>\n"
"\n",
"filename", file_->name(),
"filename_identifier", filename_identifier);
printer->Print("#include <google/protobuf/stubs/common.h>\n\n");
// Verify the protobuf library header version is compatible with the protoc
// version before going any further.
printer->Print(
"#if GOOGLE_PROTOBUF_VERSION < $min_header_version$\n"
"#error This file was generated by a newer version of protoc which is\n"
"#error incompatible with your Protocol Buffer headers. Please update\n"
"#error your headers.\n"
"#endif\n"
"#if $protoc_version$ < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION\n"
"#error This file was generated by an older version of protoc which is\n"
"#error incompatible with your Protocol Buffer headers. Please\n"
"#error regenerate this file with a newer version of protoc.\n"
"#endif\n"
"\n",
"min_header_version",
pb::SimpleItoa(pb::internal::kMinHeaderVersionForProtoc),
"protoc_version", pb::SimpleItoa(GOOGLE_PROTOBUF_VERSION));
// OK, it's now safe to #include other files.
printer->Print("#include <google/protobuf/generated_message_util.h>\n");
if (file_->message_type_count() > 0)
{
if (pbcpp::HasDescriptorMethods(file_))
printer->Print("#include <google/protobuf/message.h>\n");
else
printer->Print("#include <google/protobuf/message_lite.h>\n");
}
printer->Print(
"#include <google/protobuf/repeated_field.h>\n"
"#include <google/protobuf/extension_set.h>\n");
if (pbcpp::HasDescriptorMethods(file_) && pbcpp::HasEnumDefinitions(file_))
printer->Print("#include <google/protobuf/generated_enum_reflection.h>\n");
if (pbcpp::UseUnknownFieldSet(file_) && file_->message_type_count() > 0)
{
printer->Print("#include <google/protobuf/unknown_field_set.h>\n");
}
std::set<std::string> public_import_names;
for (int i = 0; i < file_->public_dependency_count(); i++)
public_import_names.insert(file_->public_dependency(i)->name());
for (int i = 0; i < file_->dependency_count(); i++)
{
const std::string& name = file_->dependency(i)->name();
bool public_import = (public_import_names.count(name) != 0);
printer->Print(
"#include \"$dependency$.pb.h\"$iwyu$\n",
"dependency", pbcpp::StripProto(name),
"iwyu", (public_import) ? " // IWYU pragma: export" : "");
}
if (file_->service_count() > 0)
{
printer->Print("#include \"ServiceBase.h\"\n");
printer->Print("#include \"MessageBuffer.h\"\n");
printer->Print("#include <functional>\n");
printer->Print("#include <type_traits>\n");
}
else
printer->Print("#include \"Define.h\" // for TC_PROTO_API\n");
printer->Print("// @@protoc_insertion_point(includes)\n");
// Open namespace.
GenerateNamespaceOpeners(printer);
// Forward-declare the AddDescriptors, AssignDescriptors, and ShutdownFile
// functions, so that we can declare them to be friends of each class.
printer->Print(
"\n"
"// Internal implementation detail -- do not call these.\n"
"void $dllexport_decl$ $adddescriptorsname$();\n",
"adddescriptorsname", pbcpp::GlobalAddDescriptorsName(file_->name()),
"dllexport_decl", options_.dllexport_decl);
printer->Print(
// Note that we don't put dllexport_decl on these because they are only
// called by the .pb.cc file in which they are defined.
"void $assigndescriptorsname$();\n"
"void $shutdownfilename$();\n"
"\n",
"assigndescriptorsname", pbcpp::GlobalAssignDescriptorsName(file_->name()),
"shutdownfilename", pbcpp::GlobalShutdownFileName(file_->name()));
// Generate forward declarations of classes.
for (int i = 0; i < file_->message_type_count(); i++)
message_generators_[i]->GenerateForwardDeclaration(printer);
printer->Print("\n");
// Generate enum definitions.
for (int i = 0; i < file_->message_type_count(); i++)
message_generators_[i]->GenerateEnumDefinitions(printer);
for (int i = 0; i < file_->enum_type_count(); i++)
enum_generators_[i]->GenerateDefinition(printer);
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
// Generate class definitions.
for (int i = 0; i < file_->message_type_count(); i++)
{
if (i > 0)
{
printer->Print("\n");
printer->Print(pbcpp::kThinSeparator);
printer->Print("\n");
}
message_generators_[i]->GenerateClassDefinition(printer);
}
printer->Print("\n");
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
// Generate service definitions.
for (int i = 0; i < file_->service_count(); i++)
{
if (i > 0)
{
printer->Print("\n");
printer->Print(pbcpp::kThinSeparator);
printer->Print("\n");
}
service_generators_[i]->GenerateDeclarations(printer);
}
printer->Print("\n");
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
// Declare extension identifiers.
for (int i = 0; i < file_->extension_count(); i++)
{
extension_generators_[i]->GenerateDeclaration(printer);
}
printer->Print("\n");
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
// Generate class inline methods.
for (int i = 0; i < file_->message_type_count(); i++)
{
if (i > 0)
{
printer->Print(pbcpp::kThinSeparator);
printer->Print("\n");
}
message_generators_[i]->GenerateInlineMethods(printer);
}
printer->Print(
"\n"
"// @@protoc_insertion_point(namespace_scope)\n");
// Close up namespace.
GenerateNamespaceClosers(printer);
// Emit GetEnumDescriptor specializations into google::protobuf namespace:
if (pbcpp::HasDescriptorMethods(file_))
{
// The SWIG conditional is to avoid a null-pointer dereference
// (bug 1984964) in swig-1.3.21 resulting from the following syntax:
// namespace X { void Y<Z::W>(); }
// which appears in GetEnumDescriptor() specializations.
printer->Print(
"\n"
"#ifndef SWIG\n"
"namespace google {\nnamespace protobuf {\n"
"\n");
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
}
for (int i = 0; i < file_->enum_type_count(); i++)
{
enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
}
printer->Print(
"\n"
"} // namespace google\n} // namespace protobuf\n"
"#endif // SWIG\n");
}
printer->Print(
"\n"
"// @@protoc_insertion_point(global_scope)\n"
"\n");
printer->Print(
"#endif // PROTOBUF_$filename_identifier$__INCLUDED\n",
"filename_identifier", filename_identifier);
}
void BnetFileGenerator::GenerateSource(pb::io::Printer* printer)
{
printer->Print(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
// The generated code calls accessors that might be deprecated. We don't
// want the compiler to warn in generated code.
"#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION\n"
"#include \"$basename$.pb.h\"\n"
"\n"
"#include <algorithm>\n" // for swap()
"#include <utility>\n" // for move()
"\n"
"#include <google/protobuf/stubs/common.h>\n"
"#include <google/protobuf/stubs/once.h>\n"
"#include <google/protobuf/io/coded_stream.h>\n"
"#include <google/protobuf/wire_format_lite_inl.h>\n",
"filename", file_->name(),
"basename", pbcpp::StripProto(file_->name()));
// Unknown fields implementation in lite mode uses StringOutputStream
if (!pbcpp::UseUnknownFieldSet(file_) && file_->message_type_count() > 0)
{
printer->Print(
"#include <google/protobuf/io/zero_copy_stream_impl_lite.h>\n");
}
if (pbcpp::HasDescriptorMethods(file_))
{
printer->Print(
"#include <google/protobuf/descriptor.h>\n"
"#include <google/protobuf/generated_message_reflection.h>\n"
"#include <google/protobuf/reflection_ops.h>\n"
"#include <google/protobuf/wire_format.h>\n");
}
printer->Print("#include \"Log.h\"\n");
if (file_->service_count() > 0)
{
printer->Print("#include \"Errors.h\"\n");
printer->Print("#include \"BattlenetRpcErrorCodes.h\"\n");
}
printer->Print(
"// @@protoc_insertion_point(includes)\n");
GenerateNamespaceOpeners(printer);
if (pbcpp::HasDescriptorMethods(file_))
{
printer->Print(
"\n"
"namespace {\n"
"\n");
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateDescriptorDeclarations(printer);
}
for (int i = 0; i < file_->enum_type_count(); i++)
{
printer->Print(
"const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
"name", pbcpp::ClassName(file_->enum_type(i), false));
}
for (int i = 0; i < file_->service_count(); i++)
{
printer->Print(
"const ::google::protobuf::ServiceDescriptor* $name$_descriptor_ = NULL;\n",
"name", file_->service(i)->name());
}
printer->Print(
"\n"
"} // namespace\n"
"\n");
}
// Define our externally-visible BuildDescriptors() function. (For the lite
// library, all this does is initialize default instances.)
GenerateBuildDescriptors(printer);
// Generate enums.
for (int i = 0; i < file_->enum_type_count(); i++)
{
enum_generators_[i]->GenerateMethods(printer);
}
// Generate classes.
for (int i = 0; i < file_->message_type_count(); i++)
{
printer->Print("\n");
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
message_generators_[i]->GenerateClassMethods(printer);
}
// Generate services.
for (int i = 0; i < file_->service_count(); i++)
{
if (i == 0)
printer->Print("\n");
printer->Print(pbcpp::kThickSeparator);
printer->Print("\n");
service_generators_[i]->GenerateImplementation(printer);
}
// Define extensions.
for (int i = 0; i < file_->extension_count(); i++)
{
extension_generators_[i]->GenerateDefinition(printer);
}
printer->Print(
"\n"
"// @@protoc_insertion_point(namespace_scope)\n");
GenerateNamespaceClosers(printer);
printer->Print(
"\n"
"// @@protoc_insertion_point(global_scope)\n");
}
void BnetFileGenerator::GenerateBuildDescriptors(pb::io::Printer* printer)
{
// AddDescriptors() is a file-level procedure which adds the encoded
// FileDescriptorProto for this .proto file to the global DescriptorPool for
// generated files (DescriptorPool::generated_pool()). It either runs at
// static initialization time (by default) or when default_instance() is
// called for the first time (in LITE_RUNTIME mode with
// GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER flag enabled). This procedure also
// constructs default instances and registers extensions.
//
// Its sibling, AssignDescriptors(), actually pulls the compiled
// FileDescriptor from the DescriptorPool and uses it to populate all of
// the global variables which store pointers to the descriptor objects.
// It also constructs the reflection objects. It is called the first time
// anyone calls descriptor() or GetReflection() on one of the types defined
// in the file.
// In optimize_for = LITE_RUNTIME mode, we don't generate AssignDescriptors()
// and we only use AddDescriptors() to allocate default instances.
if (pbcpp::HasDescriptorMethods(file_))
{
printer->Print(
"\n"
"void $assigndescriptorsname$() {\n",
"assigndescriptorsname", pbcpp::GlobalAssignDescriptorsName(file_->name()));
printer->Indent();
// Make sure the file has found its way into the pool. If a descriptor
// is requested *during* static init then AddDescriptors() may not have
// been called yet, so we call it manually. Note that it's fine if
// AddDescriptors() is called multiple times.
printer->Print(
"$adddescriptorsname$();\n",
"adddescriptorsname", pbcpp::GlobalAddDescriptorsName(file_->name()));
// Get the file's descriptor from the pool.
printer->Print(
"const ::google::protobuf::FileDescriptor* file =\n"
" ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(\n"
" \"$filename$\");\n"
// Note that this GOOGLE_CHECK is necessary to prevent a warning about "file"
// being unused when compiling an empty .proto file.
"GOOGLE_CHECK(file != NULL);\n",
"filename", file_->name());
// Go through all the stuff defined in this file and generated code to
// assign the global descriptor pointers based on the file descriptor.
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateDescriptorInitializer(printer, i);
}
for (int i = 0; i < file_->enum_type_count(); i++)
{
enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
}
for (int i = 0; i < file_->service_count(); i++)
{
service_generators_[i]->GenerateDescriptorInitializer(printer, i);
}
printer->Outdent();
printer->Print(
"}\n"
"\n");
// ---------------------------------------------------------------
// protobuf_AssignDescriptorsOnce(): The first time it is called, calls
// AssignDescriptors(). All later times, waits for the first call to
// complete and then returns.
printer->Print(
"namespace {\n"
"\n"
"GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);\n"
"inline void protobuf_AssignDescriptorsOnce() {\n"
" ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,\n"
" &$assigndescriptorsname$);\n"
"}\n"
"\n",
"assigndescriptorsname", pbcpp::GlobalAssignDescriptorsName(file_->name()));
// protobuf_RegisterTypes(): Calls
// MessageFactory::InternalRegisterGeneratedType() for each message type.
printer->Print(
"void protobuf_RegisterTypes(const ::std::string&) {\n"
" protobuf_AssignDescriptorsOnce();\n");
printer->Indent();
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateTypeRegistrations(printer);
}
printer->Outdent();
printer->Print(
"}\n"
"\n"
"} // namespace\n");
}
// -----------------------------------------------------------------
// ShutdownFile(): Deletes descriptors, default instances, etc. on shutdown.
printer->Print(
"\n"
"void $shutdownfilename$() {\n",
"shutdownfilename", pbcpp::GlobalShutdownFileName(file_->name()));
printer->Indent();
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateShutdownCode(printer);
}
printer->Outdent();
printer->Print(
"}\n\n");
// -----------------------------------------------------------------
// Now generate the AddDescriptors() function.
pbcpp::PrintHandlingOptionalStaticInitializers(
file_, printer,
// With static initializers.
// Note that we don't need any special synchronization in the following code
// because it is called at static init time before any threads exist.
"void $adddescriptorsname$() {\n"
" static bool already_here = false;\n"
" if (already_here) return;\n"
" already_here = true;\n"
" GOOGLE_PROTOBUF_VERIFY_VERSION;\n"
"\n",
// Without.
"void $adddescriptorsname$_impl() {\n"
" GOOGLE_PROTOBUF_VERIFY_VERSION;\n"
"\n",
// Vars.
"adddescriptorsname", pbcpp::GlobalAddDescriptorsName(file_->name()));
printer->Indent();
// Call the AddDescriptors() methods for all of our dependencies, to make
// sure they get added first.
for (int i = 0; i < file_->dependency_count(); i++)
{
const pb::FileDescriptor* dependency = file_->dependency(i);
// Print the namespace prefix for the dependency.
std::string add_desc_name = pbcpp::QualifiedFileLevelSymbol(
dependency->package(), pbcpp::GlobalAddDescriptorsName(dependency->name()));
// Call its AddDescriptors function.
printer->Print(
"$name$();\n",
"name", add_desc_name);
}
if (pbcpp::HasDescriptorMethods(file_))
{
// Embed the descriptor. We simply serialize the entire FileDescriptorProto
// and embed it as a string literal, which is parsed and built into real
// descriptors at initialization time.
pb::FileDescriptorProto file_proto;
file_->CopyTo(&file_proto);
std::string file_data;
file_proto.SerializeToString(&file_data);
printer->Print(
"::google::protobuf::DescriptorPool::InternalAddGeneratedFile(");
// Only write 40 bytes per line.
static const int kBytesPerLine = 40;
for (int i = 0; i < file_data.size(); i += kBytesPerLine)
{
printer->Print("\n \"$data$\"",
"data",
pbcpp::EscapeTrigraphs(
pb::CEscape(file_data.substr(i, kBytesPerLine))));
}
printer->Print(
", $size$);\n",
"size", pb::SimpleItoa(file_data.size()));
// Call MessageFactory::InternalRegisterGeneratedFile().
printer->Print(
"::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(\n"
" \"$filename$\", &protobuf_RegisterTypes);\n",
"filename", file_->name());
}
// Allocate and initialize default instances. This can't be done lazily
// since default instances are returned by simple accessors and are used with
// extensions. Speaking of which, we also register extensions at this time.
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateDefaultInstanceAllocator(printer);
}
for (int i = 0; i < file_->extension_count(); i++)
{
extension_generators_[i]->GenerateRegistration(printer);
}
for (int i = 0; i < file_->message_type_count(); i++)
{
message_generators_[i]->GenerateDefaultInstanceInitializer(printer);
}
printer->Print(
"::google::protobuf::internal::OnShutdown(&$shutdownfilename$);\n",
"shutdownfilename", pbcpp::GlobalShutdownFileName(file_->name()));
printer->Outdent();
printer->Print(
"}\n"
"\n");
pbcpp::PrintHandlingOptionalStaticInitializers(
file_, printer,
// With static initializers.
"// Force AddDescriptors() to be called at static initialization time.\n"
"struct StaticDescriptorInitializer_$filename$ {\n"
" StaticDescriptorInitializer_$filename$() {\n"
" $adddescriptorsname$();\n"
" }\n"
"} static_descriptor_initializer_$filename$_;\n",
// Without.
"GOOGLE_PROTOBUF_DECLARE_ONCE($adddescriptorsname$_once_);\n"
"void $adddescriptorsname$() {\n"
" ::google::protobuf::GoogleOnceInit(&$adddescriptorsname$_once_,\n"
" &$adddescriptorsname$_impl);\n"
"}\n",
// Vars.
"adddescriptorsname", pbcpp::GlobalAddDescriptorsName(file_->name()),
"filename", pbcpp::FilenameIdentifier(file_->name()));
}
void BnetFileGenerator::GenerateNamespaceOpeners(pb::io::Printer* printer)
{
if (package_parts_.size() > 0)
printer->Print("\n");
for (int i = 0; i < package_parts_.size(); i++)
{
printer->Print("namespace $part$ {\n",
"part", package_parts_[i]);
}
}
void BnetFileGenerator::GenerateNamespaceClosers(pb::io::Printer* printer)
{
if (package_parts_.size() > 0)
printer->Print("\n");
for (int i = package_parts_.size() - 1; i >= 0; i--)
{
printer->Print("} // namespace $part$\n",
"part", package_parts_[i]);
}
}
+109
View File
@@ -0,0 +1,109 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
#include <memory>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
#include "google/protobuf/compiler/cpp/cpp_field.h"
#include "google/protobuf/compiler/cpp/cpp_options.h"
class BnetServiceGenerator; // service.h
namespace google
{
namespace protobuf
{
class FileDescriptor; // descriptor.h
namespace io
{
class Printer; // printer.h
}
}
namespace protobuf
{
namespace compiler
{
namespace cpp
{
class EnumGenerator; // enum.h
class MessageGenerator; // message.h
class ExtensionGenerator; // extension.h
}
}
}
}
namespace pb = google::protobuf;
namespace pbcpp = pb::compiler::cpp;
class BnetFileGenerator
{
public:
// See generator.cc for the meaning of dllexport_decl.
explicit BnetFileGenerator(const pb::FileDescriptor* file,
const pbcpp::Options& options);
~BnetFileGenerator();
void GenerateHeader(pb::io::Printer* printer);
void GenerateSource(pb::io::Printer* printer);
private:
// Generate the BuildDescriptors() procedure, which builds all descriptors
// for types defined in the file.
void GenerateBuildDescriptors(pb::io::Printer* printer);
void GenerateNamespaceOpeners(pb::io::Printer* printer);
void GenerateNamespaceClosers(pb::io::Printer* printer);
const pb::FileDescriptor* file_;
pb::scoped_array<pb::scoped_ptr<pbcpp::MessageGenerator>> message_generators_;
pb::scoped_array<pb::scoped_ptr<pbcpp::EnumGenerator>> enum_generators_;
pb::scoped_array<pb::scoped_ptr<BnetServiceGenerator>> service_generators_;
pb::scoped_array<pb::scoped_ptr<pbcpp::ExtensionGenerator>> extension_generators_;
// E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
std::vector<std::string> package_parts_;
const pbcpp::Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(BnetFileGenerator);
};
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
@@ -0,0 +1,330 @@
//
// Created by tea on 10.03.16.
//
#include "BnetServiceGenerator.h"
#include "method_options.pb.h"
#include "service_options.pb.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include "google/protobuf/compiler/cpp/cpp_options.h"
BnetServiceGenerator::BnetServiceGenerator(pb::ServiceDescriptor const* descriptor, pbcpp::Options const& options) : descriptor_(descriptor)
{
vars_["classname"] = descriptor_->name();
vars_["full_name"] = descriptor_->full_name();
if (options.dllexport_decl.empty())
vars_["dllexport"] = "";
else
vars_["dllexport"] = options.dllexport_decl + " ";
if (descriptor_->options().HasExtension(Battlenet::service_options))
vars_["original_hash"] = " typedef std::integral_constant<uint32, 0x" + pb::ToUpper(pb::ToHex(HashServiceName(descriptor_->options().GetExtension(Battlenet::service_options).descriptor_name()))) + "u> OriginalHash;\n";
vars_["name_hash"] = " typedef std::integral_constant<uint32, 0x" + pb::ToUpper(pb::ToHex(HashServiceName(descriptor_->full_name()))) + "u> NameHash;\n";
}
BnetServiceGenerator::~BnetServiceGenerator() { }
void BnetServiceGenerator::GenerateDeclarations(pb::io::Printer* printer)
{
GenerateInterface(printer);
}
void BnetServiceGenerator::GenerateInterface(pb::io::Printer* printer)
{
printer->Print(vars_,
"class $dllexport$$classname$ : public ServiceBase\n"
"{\n"
" public:\n"
"\n"
" explicit $classname$(bool use_original_hash);\n"
" virtual ~$classname$();\n"
"\n"
"$original_hash$"
"$name_hash$");
printer->Indent();
printer->Print(vars_,
"\n"
"static google::protobuf::ServiceDescriptor const* descriptor();\n"
"\n"
"// client methods --------------------------------------------------\n"
"\n");
GenerateClientMethodSignatures(printer);
printer->Print(
"// server methods --------------------------------------------------\n"
"\n"
"void CallServerMethod(uint32 token, uint32 methodId, MessageBuffer buffer) override final;\n"
"\n");
printer->Outdent();
printer->Print(" protected:\n ");
printer->Indent();
GenerateServerMethodSignatures(printer);
printer->Outdent();
printer->Print(vars_,
"\n"
" private:\n"
" uint32 service_hash_;\n"
"\n"
" GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n"
"};\n");
}
void BnetServiceGenerator::GenerateClientMethodSignatures(pb::io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++)
{
pb::MethodDescriptor const* method = descriptor_->method(i);
if (!method->options().HasExtension(Battlenet::method_options))
continue;
std::map<std::string, std::string> sub_vars;
sub_vars["name"] = method->name();
sub_vars["full_name"] = descriptor_->name() + "." + method->name();
sub_vars["method_id"] = pb::SimpleItoa(method->options().GetExtension(Battlenet::method_options).id());
sub_vars["input_type"] = pbcpp::ClassName(method->input_type(), true);
sub_vars["output_type"] = pbcpp::ClassName(method->output_type(), true);
sub_vars["input_type_name"] = method->input_type()->full_name();
if (method->output_type()->name() != "NO_RESPONSE")
printer->Print(sub_vars, "void $name$($input_type$ const* request, std::function<void($output_type$ const*)> responseCallback);\n");
else
printer->Print(sub_vars, "void $name$($input_type$ const* request);\n");
}
}
void BnetServiceGenerator::GenerateServerMethodSignatures(pb::io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++)
{
pb::MethodDescriptor const* method = descriptor_->method(i);
if (!method->options().HasExtension(Battlenet::method_options))
continue;
std::map<std::string, std::string> sub_vars;
sub_vars["name"] = method->name();
sub_vars["input_type"] = pbcpp::ClassName(method->input_type(), true);
sub_vars["output_type"] = pbcpp::ClassName(method->output_type(), true);
if (method->output_type()->name() != "NO_RESPONSE")
printer->Print(sub_vars, "virtual uint32 Handle$name$($input_type$ const* request, $output_type$* response, std::function<void(ServiceBase*, uint32, ::google::protobuf::Message const*)>& continuation);\n");
else
printer->Print(sub_vars, "virtual uint32 Handle$name$($input_type$ const* request);\n");
}
}
// ===================================================================
void BnetServiceGenerator::GenerateDescriptorInitializer(pb::io::Printer* printer, int index)
{
std::map<std::string, std::string> vars;
vars["classname"] = descriptor_->name();
vars["index"] = pb::SimpleItoa(index);
printer->Print(vars, "$classname$_descriptor_ = file->service($index$);\n");
}
// ===================================================================
void BnetServiceGenerator::GenerateImplementation(pb::io::Printer* printer)
{
printer->Print(vars_,
"$classname$::$classname$(bool use_original_hash) : service_hash_(use_original_hash ? OriginalHash::value : NameHash::value) {\n"
"}\n"
"\n"
"$classname$::~$classname$() {\n"
"}\n"
"\n"
"google::protobuf::ServiceDescriptor const* $classname$::descriptor() {\n"
" protobuf_AssignDescriptorsOnce();\n"
" return $classname$_descriptor_;\n"
"}\n"
"\n");
GenerateClientMethodImplementations(printer);
GenerateServerCallMethod(printer);
GenerateServerImplementations(printer);
}
void BnetServiceGenerator::GenerateClientMethodImplementations(pb::io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++)
{
pb::MethodDescriptor const* method = descriptor_->method(i);
if (!method->options().HasExtension(Battlenet::method_options))
continue;
std::map<std::string, std::string> sub_vars;
sub_vars["classname"] = vars_["classname"];
sub_vars["name"] = method->name();
sub_vars["full_name"] = descriptor_->name() + "." + method->name();
sub_vars["method_id"] = pb::SimpleItoa(method->options().GetExtension(Battlenet::method_options).id());
sub_vars["input_type"] = pbcpp::ClassName(method->input_type(), true);
sub_vars["output_type"] = pbcpp::ClassName(method->output_type(), true);
sub_vars["input_type_name"] = method->input_type()->full_name();
if (method->output_type()->name() != "NO_RESPONSE")
{
printer->Print(sub_vars,
"void $classname$::$name$($input_type$ const* request, std::function<void($output_type$ const*)> responseCallback) {\n"
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Server called client method $full_name$($input_type_name${ %s })\",\n"
" GetCallerInfo().c_str(), request->ShortDebugString().c_str());\n"
" std::function<void(MessageBuffer)> callback = [responseCallback](MessageBuffer buffer) -> void {\n"
" $output_type$ response;\n"
" if (response.ParseFromArray(buffer.GetReadPointer(), buffer.GetActiveSize()))\n"
" responseCallback(&response);\n"
" };\n"
" SendRequest(service_hash_, $method_id$, request, std::move(callback));\n"
"}\n"
"\n");
}
else
{
printer->Print(sub_vars,
"void $classname$::$name$($input_type$ const* request) {\n"
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Server called client method $full_name$($input_type_name${ %s })\",\n"
" GetCallerInfo().c_str(), request->ShortDebugString().c_str());\n"
" SendRequest(service_hash_, $method_id$, request);\n"
"}\n"
"\n");
}
}
}
void BnetServiceGenerator::GenerateServerCallMethod(pb::io::Printer* printer)
{
printer->Print(vars_,
"void $classname$::CallServerMethod(uint32 token, uint32 methodId, MessageBuffer buffer) {\n"
" switch(methodId) {\n");
for (int i = 0; i < descriptor_->method_count(); i++)
{
pb::MethodDescriptor const* method = descriptor_->method(i);
if (!method->options().HasExtension(Battlenet::method_options))
continue;
std::map<std::string, std::string> sub_vars;
sub_vars["classname"] = vars_["classname"];
sub_vars["name"] = method->name();
sub_vars["full_name"] = descriptor_->name() + "." + method->name();
sub_vars["method_id"] = pb::SimpleItoa(method->options().GetExtension(Battlenet::method_options).id());
sub_vars["input_type"] = pbcpp::ClassName(method->input_type(), true);
sub_vars["output_type"] = pbcpp::ClassName(method->output_type(), true);
sub_vars["input_type_name"] = method->input_type()->full_name();
sub_vars["output_type_name"] = method->output_type()->full_name();
printer->Print(sub_vars,
" case $method_id$: {\n"
" $input_type$ request;\n"
" if (!request.ParseFromArray(buffer.GetReadPointer(), buffer.GetActiveSize())) {\n"
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Failed to parse request for $full_name$ server method call.\", GetCallerInfo().c_str());\n"
" SendResponse(service_hash_, $method_id$, token, ERROR_RPC_MALFORMED_REQUEST);\n"
" return;\n"
" }\n"
);
if (method->output_type()->name() != "NO_RESPONSE")
{
printer->Print(sub_vars,
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Client called server method $full_name$($input_type_name${ %s }).\",\n"
" GetCallerInfo().c_str(), request.ShortDebugString().c_str());\n"
" std::function<void(ServiceBase*, uint32, ::google::protobuf::Message const*)> continuation = [token](ServiceBase* service, uint32 status, ::google::protobuf::Message const* response)\n"
" {\n"
" ASSERT(response->GetDescriptor() == $output_type$::descriptor());\n"
" $classname$* self = static_cast<$classname$*>(service);\n"
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Client called server method $full_name$() returned $output_type_name${ %s } status %u.\",\n"
" self->GetCallerInfo().c_str(), response->ShortDebugString().c_str(), status);\n"
" if (!status)\n"
" self->SendResponse(self->service_hash_, $method_id$, token, response);\n"
" else\n"
" self->SendResponse(self->service_hash_, $method_id$, token, status);\n"
" };\n"
" $output_type$ response;\n"
" uint32 status = Handle$name$(&request, &response, continuation);\n"
" if (continuation)\n"
" continuation(this, status, &response);\n"
);
}
else
{
printer->Print(sub_vars,
" uint32 status = Handle$name$(&request);\n"
" TC_LOG_DEBUG(\"service.protobuf\", \"%s Client called server method $full_name$($input_type_name${ %s }) status %u.\",\n"
" GetCallerInfo().c_str(), request.ShortDebugString().c_str(), status);\n"
" if (status)\n"
" SendResponse(service_hash_, $method_id$, token, status);\n");
}
printer->Print(sub_vars,
" break;\n"
" }\n");
}
printer->Print(vars_,
" default:\n"
" TC_LOG_ERROR(\"service.protobuf\", \"Bad method id %u.\", methodId);\n"
" SendResponse(service_hash_, methodId, token, ERROR_RPC_INVALID_METHOD);\n"
" break;\n"
" }\n"
"}\n"
"\n");
}
void BnetServiceGenerator::GenerateServerImplementations(pb::io::Printer* printer)
{
for (int i = 0; i < descriptor_->method_count(); i++)
{
pb::MethodDescriptor const* method = descriptor_->method(i);
if (!method->options().HasExtension(Battlenet::method_options))
continue;
std::map<std::string, std::string> sub_vars;
sub_vars["classname"] = vars_["classname"];
sub_vars["name"] = method->name();
sub_vars["full_name"] = descriptor_->name() + "." + method->name();
sub_vars["input_type"] = pbcpp::ClassName(method->input_type(), true);
sub_vars["output_type"] = pbcpp::ClassName(method->output_type(), true);
if (method->output_type()->name() != "NO_RESPONSE")
{
printer->Print(sub_vars, "uint32 $classname$::Handle$name$($input_type$ const* request, $output_type$* response, std::function<void(ServiceBase*, uint32, ::google::protobuf::Message const*)>& continuation) {\n"
" TC_LOG_ERROR(\"service.protobuf\", \"%s Client tried to call not implemented method $full_name$({ %s })\",\n"
" GetCallerInfo().c_str(), request->ShortDebugString().c_str());\n"
" return ERROR_RPC_NOT_IMPLEMENTED;\n"
"}\n"
"\n");
}
else
{
printer->Print(sub_vars, "uint32 $classname$::Handle$name$($input_type$ const* request) {\n"
" TC_LOG_ERROR(\"service.protobuf\", \"%s Client tried to call not implemented method $full_name$({ %s })\",\n"
" GetCallerInfo().c_str(), request->ShortDebugString().c_str());\n"
" return ERROR_RPC_NOT_IMPLEMENTED;\n"
"}\n"
"\n");
}
}
}
std::uint32_t BnetServiceGenerator::HashServiceName(std::string const& name)
{
std::uint32_t hash = 0x811C9DC5;
for (std::size_t i = 0; i < name.length(); ++i)
{
hash ^= name[i];
hash *= 0x1000193;
}
return hash;
}
@@ -0,0 +1,86 @@
//
// Created by tea on 10.03.16.
//
#ifndef PROTOC_BNET_BNETSERVICEGENERATOR_H
#define PROTOC_BNET_BNETSERVICEGENERATOR_H
#include <google/protobuf/stubs/common.h>
#include <cstdint>
#include <string>
#include <map>
namespace google
{
namespace protobuf
{
class ServiceDescriptor;
namespace io
{
class Printer;
}
namespace compiler
{
namespace cpp
{
struct Options;
}
}
}
}
namespace pb = google::protobuf;
namespace pbcpp = pb::compiler::cpp;
class BnetServiceGenerator
{
public:
// See generator.cc for the meaning of dllexport_decl.
BnetServiceGenerator(const pb::ServiceDescriptor* descriptor,
const pbcpp::Options& options);
~BnetServiceGenerator();
// Header stuff.
// Generate the class definitions for the service's interface and the
// stub implementation.
void GenerateDeclarations(pb::io::Printer* printer);
// Source file stuff.
// Generate code that initializes the global variable storing the service's
// descriptor.
void GenerateDescriptorInitializer(pb::io::Printer* printer, int index);
// Generate implementations of everything declared by GenerateDeclarations().
void GenerateImplementation(pb::io::Printer* printer);
private:
// Header stuff.
// Generate the service abstract interface.
void GenerateInterface(pb::io::Printer* printer);
// Prints signatures for all methods in the
void GenerateClientMethodSignatures(pb::io::Printer* printer);
void GenerateServerMethodSignatures(pb::io::Printer* printer);
// Source file stuff.
void GenerateClientMethodImplementations(pb::io::Printer* printer);
// Generate the CallMethod() method of the service.
void GenerateServerCallMethod(pb::io::Printer* printer);
void GenerateServerImplementations(pb::io::Printer* printer);
std::uint32_t HashServiceName(std::string const& name);
const pb::ServiceDescriptor* descriptor_;
std::map<std::string, std::string> vars_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(BnetServiceGenerator);
};
#endif //PROTOC_BNET_BNETSERVICEGENERATOR_H
+32
View File
@@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 3.0)
project(protoc_bnet)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
find_package(Protobuf REQUIRED)
file(GLOB_RECURSE SOURCE_PROTOBUF_CPP google/protobuf/*.cc)
set(SOURCE_FILES
main.cpp
BnetCodeGenerator.cpp
BnetFileGenerator.cpp
BnetServiceGenerator.cpp
method_options.pb.cc
service_options.pb.cc
${SOURCE_PROTOBUF_CPP})
include_directories(${CMAKE_SOURCE_DIR} ${PROTOBUF_INCLUDE_DIRS})
add_executable(protoc-gen-bnet ${SOURCE_FILES})
target_link_libraries(protoc-gen-bnet ${PROTOBUF_PROTOC_LIBRARIES} ${PROTOBUF_LIBRARIES})
set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR})
add_custom_target(install_plugin
make install
DEPENDS protoc-gen-bnet
COMMENT "Installing protoc_bnet")
install(TARGETS protoc-gen-bnet DESTINATION bin)
+31
View File
@@ -0,0 +1,31 @@
/* protobuf config.h for MSVC. On other platforms, this is generated
* automatically by autoheader / autoconf / configure. */
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
/* the location of <hash_map> */
#define HASH_MAP_H <hash_map>
/* the namespace of hash_map/hash_set */
// Apparently Microsoft decided to move hash_map *back* to the std namespace
// in MSVC 2010:
// http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx
// TODO(kenton): Use unordered_map instead, which is available in MSVC 2010.
#if _MSC_VER < 1310 || _MSC_VER >= 1600
#define HASH_NAMESPACE std
#else
#define HASH_NAMESPACE stdext
#endif
/* the location of <hash_set> */
#define HASH_SET_H <hash_set>
/* define if the compiler has hash_map */
#define HAVE_HASH_MAP 1
/* define if the compiler has hash_set */
#define HAVE_HASH_SET 1
/* define if you want to use zlib. See readme.txt for additional
* requirements. */
// #define HAVE_ZLIB 1
+6
View File
@@ -0,0 +1,6 @@
FOR %%P IN (proto\global_extensions\*.proto) DO (
protoc.exe --plugin=protoc-gen-bnet=protoc-gen-bnet.exe --bnet_out=dllexport_decl=TC_PROTO_API:buildproto -Iproto %%P
)
FOR %%P IN (proto\*.proto) DO (
protoc.exe --plugin=protoc-gen-bnet=protoc-gen-bnet.exe --bnet_out=dllexport_decl=TC_PROTO_API:buildproto -Iproto %%P
)
@@ -0,0 +1,288 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <set>
#include <map>
#include "google/protobuf/compiler/cpp/cpp_enum.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
// The GOOGLE_ARRAYSIZE constant is the max enum value plus 1. If the max enum value
// is kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the
// generation of the GOOGLE_ARRAYSIZE constant.
bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) {
int32 max_value = descriptor->value(0)->number();
for (int i = 0; i < descriptor->value_count(); i++) {
if (descriptor->value(i)->number() > max_value) {
max_value = descriptor->value(i)->number();
}
}
return max_value != kint32max;
}
} // namespace
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
classname_(ClassName(descriptor, false)),
options_(options),
generate_array_size_(ShouldGenerateArraySize(descriptor)) {
}
EnumGenerator::~EnumGenerator() {}
void EnumGenerator::GenerateDefinition(io::Printer* printer) {
map<string, string> vars;
vars["classname"] = classname_;
vars["short_name"] = descriptor_->name();
printer->Print(vars, "enum $classname$ {\n");
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
const EnumValueDescriptor* max_value = descriptor_->value(0);
for (int i = 0; i < descriptor_->value_count(); i++) {
vars["name"] = descriptor_->value(i)->name();
// In C++, an value of -2147483648 gets interpreted as the negative of
// 2147483648, and since 2147483648 can't fit in an integer, this produces a
// compiler warning. This works around that issue.
vars["number"] = Int32ToString(descriptor_->value(i)->number());
vars["prefix"] = (descriptor_->containing_type() == NULL) ?
"" : classname_ + "_";
if (i > 0) printer->Print(",\n");
printer->Print(vars, "$prefix$$name$ = $number$");
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
}
if (descriptor_->value(i)->number() > max_value->number()) {
max_value = descriptor_->value(i);
}
}
printer->Outdent();
printer->Print("\n};\n");
vars["min_name"] = min_value->name();
vars["max_name"] = max_value->name();
if (options_.dllexport_decl.empty()) {
vars["dllexport"] = "";
} else {
vars["dllexport"] = options_.dllexport_decl + " ";
}
printer->Print(vars,
"$dllexport$bool $classname$_IsValid(int value);\n"
"const $classname$ $prefix$$short_name$_MIN = $prefix$$min_name$;\n"
"const $classname$ $prefix$$short_name$_MAX = $prefix$$max_name$;\n");
if (generate_array_size_) {
printer->Print(vars,
"const int $prefix$$short_name$_ARRAYSIZE = "
"$prefix$$short_name$_MAX + 1;\n\n");
}
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(vars,
"$dllexport$const ::google::protobuf::EnumDescriptor* $classname$_descriptor();\n");
// The _Name and _Parse methods
printer->Print(vars,
"inline const ::std::string& $classname$_Name($classname$ value) {\n"
" return ::google::protobuf::internal::NameOfEnum(\n"
" $classname$_descriptor(), value);\n"
"}\n");
printer->Print(vars,
"inline bool $classname$_Parse(\n"
" const ::std::string& name, $classname$* value) {\n"
" return ::google::protobuf::internal::ParseNamedEnum<$classname$>(\n"
" $classname$_descriptor(), name, value);\n"
"}\n");
}
}
void EnumGenerator::
GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(
"template <> struct is_proto_enum< $classname$> : ::google::protobuf::internal::true_type {};\n"
"template <>\n"
"inline const EnumDescriptor* GetEnumDescriptor< $classname$>() {\n"
" return $classname$_descriptor();\n"
"}\n",
"classname", ClassName(descriptor_, true));
}
}
void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
map<string, string> vars;
vars["nested_name"] = descriptor_->name();
vars["classname"] = classname_;
printer->Print(vars, "typedef $classname$ $nested_name$;\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
vars["tag"] = descriptor_->value(j)->name();
printer->Print(vars,
"static const $nested_name$ $tag$ = $classname$_$tag$;\n");
}
printer->Print(vars,
"static inline bool $nested_name$_IsValid(int value) {\n"
" return $classname$_IsValid(value);\n"
"}\n"
"static const $nested_name$ $nested_name$_MIN =\n"
" $classname$_$nested_name$_MIN;\n"
"static const $nested_name$ $nested_name$_MAX =\n"
" $classname$_$nested_name$_MAX;\n");
if (generate_array_size_) {
printer->Print(vars,
"static const int $nested_name$_ARRAYSIZE =\n"
" $classname$_$nested_name$_ARRAYSIZE;\n");
}
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(vars,
"static inline const ::google::protobuf::EnumDescriptor*\n"
"$nested_name$_descriptor() {\n"
" return $classname$_descriptor();\n"
"}\n");
printer->Print(vars,
"static inline const ::std::string& $nested_name$_Name($nested_name$ value) {\n"
" return $classname$_Name(value);\n"
"}\n");
printer->Print(vars,
"static inline bool $nested_name$_Parse(const ::std::string& name,\n"
" $nested_name$* value) {\n"
" return $classname$_Parse(name, value);\n"
"}\n");
}
}
void EnumGenerator::GenerateDescriptorInitializer(
io::Printer* printer, int index) {
map<string, string> vars;
vars["classname"] = classname_;
vars["index"] = SimpleItoa(index);
if (descriptor_->containing_type() == NULL) {
printer->Print(vars,
"$classname$_descriptor_ = file->enum_type($index$);\n");
} else {
vars["parent"] = ClassName(descriptor_->containing_type(), false);
printer->Print(vars,
"$classname$_descriptor_ = $parent$_descriptor_->enum_type($index$);\n");
}
}
void EnumGenerator::GenerateMethods(io::Printer* printer) {
map<string, string> vars;
vars["classname"] = classname_;
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(vars,
"const ::google::protobuf::EnumDescriptor* $classname$_descriptor() {\n"
" protobuf_AssignDescriptorsOnce();\n"
" return $classname$_descriptor_;\n"
"}\n");
}
printer->Print(vars,
"bool $classname$_IsValid(int value) {\n"
" switch(value) {\n");
// Multiple values may have the same number. Make sure we only cover
// each number once by first constructing a set containing all valid
// numbers, then printing a case statement for each element.
set<int> numbers;
for (int j = 0; j < descriptor_->value_count(); j++) {
const EnumValueDescriptor* value = descriptor_->value(j);
numbers.insert(value->number());
}
for (set<int>::iterator iter = numbers.begin();
iter != numbers.end(); ++iter) {
printer->Print(
" case $number$:\n",
"number", Int32ToString(*iter));
}
printer->Print(vars,
" return true;\n"
" default:\n"
" return false;\n"
" }\n"
"}\n"
"\n");
if (descriptor_->containing_type() != NULL) {
// We need to "define" the static constants which were declared in the
// header, to give the linker a place to put them. Or at least the C++
// standard says we have to. MSVC actually insists tha we do _not_ define
// them again in the .cc file.
printer->Print("#ifndef _MSC_VER\n");
vars["parent"] = ClassName(descriptor_->containing_type(), false);
vars["nested_name"] = descriptor_->name();
for (int i = 0; i < descriptor_->value_count(); i++) {
vars["value"] = descriptor_->value(i)->name();
printer->Print(vars,
"const $classname$ $parent$::$value$;\n");
}
printer->Print(vars,
"const $classname$ $parent$::$nested_name$_MIN;\n"
"const $classname$ $parent$::$nested_name$_MAX;\n");
if (generate_array_size_) {
printer->Print(vars,
"const int $parent$::$nested_name$_ARRAYSIZE;\n");
}
printer->Print("#endif // _MSC_VER\n");
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,103 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
#include <string>
#include "google/protobuf/compiler/cpp/cpp_options.h"
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace cpp {
class EnumGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit EnumGenerator(const EnumDescriptor* descriptor,
const Options& options);
~EnumGenerator();
// Header stuff.
// Generate header code defining the enum. This code should be placed
// within the enum's package namespace, but NOT within any class, even for
// nested enums.
void GenerateDefinition(io::Printer* printer);
// Generate specialization of GetEnumDescriptor<MyEnum>().
// Precondition: in ::google::protobuf namespace.
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
// For enums nested within a message, generate code to import all the enum's
// symbols (e.g. the enum type name, all its values, etc.) into the class's
// namespace. This should be placed inside the class definition in the
// header.
void GenerateSymbolImports(io::Printer* printer);
// Source file stuff.
// Generate code that initializes the global variable storing the enum's
// descriptor.
void GenerateDescriptorInitializer(io::Printer* printer, int index);
// Generate non-inline methods related to the enum, such as IsValidValue().
// Goes in the .cc file.
void GenerateMethods(io::Printer* printer);
private:
const EnumDescriptor* descriptor_;
string classname_;
Options options_;
// whether to generate the *_ARRAYSIZE constant.
bool generate_array_size_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
@@ -0,0 +1,433 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_enum_field.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
const EnumValueDescriptor* default_value = descriptor->default_value_enum();
(*variables)["type"] = ClassName(descriptor->enum_type(), true);
(*variables)["default"] = Int32ToString(default_value->number());
(*variables)["full_name"] = descriptor->full_name();
}
} // namespace
// ===================================================================
EnumFieldGenerator::
EnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetEnumVariables(descriptor, &variables_, options);
}
EnumFieldGenerator::~EnumFieldGenerator() {}
void EnumFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_, "int $name$_;\n");
}
void EnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $name$() const$deprecation$;\n"
"inline void set_$name$($type$ value)$deprecation$;\n");
}
void EnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_);\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" assert($type$_IsValid(value));\n"
" set_has_$name$();\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void EnumFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $default$;\n");
}
void EnumFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "set_$name$(from.$name$());\n");
}
void EnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
}
void EnumFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $default$;\n");
}
void EnumFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"int value;\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n"
"if ($type$_IsValid(value)) {\n"
" set_$name$(static_cast< $type$ >(value));\n");
if (UseUnknownFieldSet(descriptor_->file())) {
printer->Print(variables_,
"} else {\n"
" mutable_unknown_fields()->AddVarint($number$, value);\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32(tag);\n"
" unknown_fields_stream.WriteVarint32(value);\n");
}
printer->Print(variables_,
"}\n");
}
void EnumFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::WriteEnum(\n"
" $number$, this->$name$(), output);\n");
}
void EnumFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
" $number$, this->$name$(), target);\n");
}
void EnumFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::EnumSize(this->$name$());\n");
}
// ===================================================================
EnumOneofFieldGenerator::
EnumOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: EnumFieldGenerator(descriptor, options) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {}
void EnumOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" if (has_$name$()) {\n"
" return static_cast< $type$ >($oneof_prefix$$name$_);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" assert($type$_IsValid(value));\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
" $oneof_prefix$$name$_ = value;\n"
"}\n");
}
void EnumOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
}
void EnumOneofFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
// Don't print any swapping code. Swapping the union will swap this field.
}
void EnumOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(variables_,
" $classname$_default_oneof_instance_->$name$_ = $default$;\n");
}
// ===================================================================
RepeatedEnumFieldGenerator::
RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetEnumVariables(descriptor, &variables_, options);
}
RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {}
void RepeatedEnumFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::RepeatedField<int> $name$_;\n");
if (descriptor_->options().packed()
&& HasGeneratedMethods(descriptor_->file())) {
printer->Print(variables_,
"mutable int _$name$_cached_byte_size_;\n");
}
}
void RepeatedEnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $name$(int index) const$deprecation$;\n"
"inline void set_$name$(int index, $type$ value)$deprecation$;\n"
"inline void add_$name$($type$ value)$deprecation$;\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedField<int>& $name$() const$deprecation$;\n"
"inline ::google::protobuf::RepeatedField<int>* mutable_$name$()$deprecation$;\n");
}
void RepeatedEnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_.Get(index));\n"
"}\n"
"inline void $classname$::set_$name$(int index, $type$ value) {\n"
" assert($type$_IsValid(value));\n"
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"inline void $classname$::add_$name$($type$ value) {\n"
" assert($type$_IsValid(value));\n"
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedField<int>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::google::protobuf::RepeatedField<int>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Clear();\n");
}
void RepeatedEnumFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedEnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
}
void RepeatedEnumFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
if (descriptor_->options().packed()) {
printer->Print(variables_, "_$name$_cached_byte_size_ = 0;\n");
}
}
void RepeatedEnumFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
// Don't use ReadRepeatedPrimitive here so that the enum can be validated.
printer->Print(variables_,
"int value;\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n"
"if ($type$_IsValid(value)) {\n"
" add_$name$(static_cast< $type$ >(value));\n");
if (UseUnknownFieldSet(descriptor_->file())) {
printer->Print(variables_,
"} else {\n"
" mutable_unknown_fields()->AddVarint($number$, value);\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32(tag);\n"
" unknown_fields_stream.WriteVarint32(value);\n");
}
printer->Print("}\n");
}
void RepeatedEnumFieldGenerator::
GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
if (!descriptor_->options().packed()) {
// We use a non-inlined implementation in this case, since this path will
// rarely be executed.
printer->Print(variables_,
"DO_((::google::protobuf::internal::WireFormatLite::ReadPackedEnumNoInline(\n"
" input,\n"
" &$type$_IsValid,\n"
" this->mutable_$name$())));\n");
} else {
printer->Print(variables_,
"::google::protobuf::uint32 length;\n"
"DO_(input->ReadVarint32(&length));\n"
"::google::protobuf::io::CodedInputStream::Limit limit = "
"input->PushLimit(length);\n"
"while (input->BytesUntilLimit() > 0) {\n"
" int value;\n"
" DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
" input, &value)));\n"
" if ($type$_IsValid(value)) {\n"
" add_$name$(static_cast< $type$ >(value));\n"
" }\n"
"}\n"
"input->PopLimit(limit);\n");
}
}
void RepeatedEnumFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->options().packed()) {
// Write the tag and the size.
printer->Print(variables_,
"if (this->$name$_size() > 0) {\n"
" ::google::protobuf::internal::WireFormatLite::WriteTag(\n"
" $number$,\n"
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" output);\n"
" output->WriteVarint32(_$name$_cached_byte_size_);\n"
"}\n");
}
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag(\n"
" this->$name$(i), output);\n");
} else {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::WriteEnum(\n"
" $number$, this->$name$(i), output);\n");
}
printer->Print("}\n");
}
void RepeatedEnumFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (descriptor_->options().packed()) {
// Write the tag and the size.
printer->Print(variables_,
"if (this->$name$_size() > 0) {\n"
" target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n"
" $number$,\n"
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray("
" _$name$_cached_byte_size_, target);\n"
"}\n");
}
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
" target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n"
" this->$name$(i), target);\n");
} else {
printer->Print(variables_,
" target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
" $number$, this->$name$(i), target);\n");
}
printer->Print("}\n");
}
void RepeatedEnumFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
" int data_size = 0;\n");
printer->Indent();
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n"
" this->$name$(i));\n"
"}\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
"}\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
"_$name$_cached_byte_size_ = data_size;\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
"total_size += data_size;\n");
} else {
printer->Print(variables_,
"total_size += $tag_size$ * this->$name$_size() + data_size;\n");
}
printer->Outdent();
printer->Print("}\n");
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,122 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
#include <map>
#include <string>
#include "google/protobuf/compiler/cpp/cpp_field.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
class EnumFieldGenerator : public FieldGenerator {
public:
explicit EnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~EnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
protected:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
};
class EnumOneofFieldGenerator : public EnumFieldGenerator {
public:
explicit EnumOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~EnumOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumOneofFieldGenerator);
};
class RepeatedEnumFieldGenerator : public FieldGenerator {
public:
explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~RepeatedEnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
@@ -0,0 +1,210 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_extension.h"
#include <map>
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include "google/protobuf/stubs/strutil.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
// Returns the fully-qualified class name of the message that this field
// extends. This function is used in the Google-internal code to handle some
// legacy cases.
string ExtendeeClassName(const FieldDescriptor* descriptor) {
const Descriptor* extendee = descriptor->containing_type();
return ClassName(extendee, true);
}
} // anonymous namespace
ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
options_(options) {
// Construct type_traits_.
if (descriptor_->is_repeated()) {
type_traits_ = "Repeated";
}
switch (descriptor_->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
type_traits_.append("EnumTypeTraits< ");
type_traits_.append(ClassName(descriptor_->enum_type(), true));
type_traits_.append(", ");
type_traits_.append(ClassName(descriptor_->enum_type(), true));
type_traits_.append("_IsValid>");
break;
case FieldDescriptor::CPPTYPE_STRING:
type_traits_.append("StringTypeTraits");
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
type_traits_.append("MessageTypeTraits< ");
type_traits_.append(ClassName(descriptor_->message_type(), true));
type_traits_.append(" >");
break;
default:
type_traits_.append("PrimitiveTypeTraits< ");
type_traits_.append(PrimitiveTypeName(descriptor_->cpp_type()));
type_traits_.append(" >");
break;
}
}
ExtensionGenerator::~ExtensionGenerator() {}
void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) {
map<string, string> vars;
vars["extendee" ] = ExtendeeClassName(descriptor_);
vars["number" ] = SimpleItoa(descriptor_->number());
vars["type_traits" ] = type_traits_;
vars["name" ] = descriptor_->name();
vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
vars["packed" ] = descriptor_->options().packed() ? "true" : "false";
vars["constant_name"] = FieldConstantName(descriptor_);
// If this is a class member, it needs to be declared "static". Otherwise,
// it needs to be "extern". In the latter case, it also needs the DLL
// export/import specifier.
if (descriptor_->extension_scope() == NULL) {
vars["qualifier"] = "extern";
if (!options_.dllexport_decl.empty()) {
vars["qualifier"] = options_.dllexport_decl + " " + vars["qualifier"];
}
} else {
vars["qualifier"] = "static";
}
printer->Print(vars,
"static const int $constant_name$ = $number$;\n"
"$qualifier$ ::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n"
" ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
" $name$;\n"
);
}
void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
// If this is a class member, it needs to be declared in its class scope.
string scope = (descriptor_->extension_scope() == NULL) ? "" :
ClassName(descriptor_->extension_scope(), false) + "::";
string name = scope + descriptor_->name();
map<string, string> vars;
vars["extendee" ] = ExtendeeClassName(descriptor_);
vars["type_traits" ] = type_traits_;
vars["name" ] = name;
vars["constant_name"] = FieldConstantName(descriptor_);
vars["default" ] = DefaultValue(descriptor_);
vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
vars["packed" ] = descriptor_->options().packed() ? "true" : "false";
vars["scope" ] = scope;
if (descriptor_->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
// We need to declare a global string which will contain the default value.
// We cannot declare it at class scope because that would require exposing
// it in the header which would be annoying for other reasons. So we
// replace :: with _ in the name and declare it as a global.
string global_name = StringReplace(name, "::", "_", true);
vars["global_name"] = global_name;
printer->Print(vars,
"const ::std::string $global_name$_default($default$);\n");
// Update the default to refer to the string global.
vars["default"] = global_name + "_default";
}
// Likewise, class members need to declare the field constant variable.
if (descriptor_->extension_scope() != NULL) {
printer->Print(vars,
"#ifndef _MSC_VER\n"
"const int $scope$$constant_name$;\n"
"#endif\n");
}
printer->Print(vars,
"::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n"
" ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
" $name$($constant_name$, $default$);\n");
}
void ExtensionGenerator::GenerateRegistration(io::Printer* printer) {
map<string, string> vars;
vars["extendee" ] = ExtendeeClassName(descriptor_);
vars["number" ] = SimpleItoa(descriptor_->number());
vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
vars["is_repeated"] = descriptor_->is_repeated() ? "true" : "false";
vars["is_packed" ] = (descriptor_->is_repeated() &&
descriptor_->options().packed())
? "true" : "false";
switch (descriptor_->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
printer->Print(vars,
"::google::protobuf::internal::ExtensionSet::RegisterEnumExtension(\n"
" &$extendee$::default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(
" &$type$_IsValid);\n",
"type", ClassName(descriptor_->enum_type(), true));
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
printer->Print(vars,
"::google::protobuf::internal::ExtensionSet::RegisterMessageExtension(\n"
" &$extendee$::default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(
" &$type$::default_instance());\n",
"type", ClassName(descriptor_->message_type(), true));
break;
default:
printer->Print(vars,
"::google::protobuf::internal::ExtensionSet::RegisterExtension(\n"
" &$extendee$::default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$);\n");
break;
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,86 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
#include <string>
#include <google/protobuf/stubs/common.h>
#include "google/protobuf/compiler/cpp/cpp_options.h"
namespace google {
namespace protobuf {
class FieldDescriptor; // descriptor.h
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace cpp {
// Generates code for an extension, which may be within the scope of some
// message or may be at file scope. This is much simpler than FieldGenerator
// since extensions are just simple identifiers with interesting types.
class ExtensionGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit ExtensionGenerator(const FieldDescriptor* desycriptor,
const Options& options);
~ExtensionGenerator();
// Header stuff.
void GenerateDeclaration(io::Printer* printer);
// Source file stuff.
void GenerateDefinition(io::Printer* printer);
// Generate code to register the extension.
void GenerateRegistration(io::Printer* printer);
private:
const FieldDescriptor* descriptor_;
string type_traits_;
Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
@@ -0,0 +1,166 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_field.h"
#include <memory>
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include "google/protobuf/compiler/cpp/cpp_primitive_field.h"
#include "google/protobuf/compiler/cpp/cpp_string_field.h"
#include "google/protobuf/compiler/cpp/cpp_enum_field.h"
#include "google/protobuf/compiler/cpp/cpp_message_field.h"
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/common.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
using internal::WireFormat;
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options) {
(*variables)["name"] = FieldName(descriptor);
(*variables)["index"] = SimpleItoa(descriptor->index());
(*variables)["number"] = SimpleItoa(descriptor->number());
(*variables)["classname"] = ClassName(FieldScope(descriptor), false);
(*variables)["declared_type"] = DeclaredTypeMethodName(descriptor->type());
(*variables)["tag_size"] = SimpleItoa(
WireFormat::TagSize(descriptor->number(), descriptor->type()));
(*variables)["deprecation"] = descriptor->options().deprecated()
? " PROTOBUF_DEPRECATED" : "";
(*variables)["cppget"] = "Get";
}
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
map<string, string>* variables) {
(*variables)["oneof_prefix"] = descriptor->containing_oneof()->name() + "_.";
(*variables)["oneof_name"] = descriptor->containing_oneof()->name();
}
FieldGenerator::~FieldGenerator() {}
void FieldGenerator::
GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
// Reaching here indicates a bug. Cases are:
// - This FieldGenerator should support packing, but this method should be
// overridden.
// - This FieldGenerator doesn't support packing, and this method should
// never have been called.
GOOGLE_LOG(FATAL) << "GenerateMergeFromCodedStreamWithPacking() "
<< "called on field generator that does not support packing.";
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
field_generators_(
new scoped_ptr<FieldGenerator>[descriptor->field_count()]) {
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
field_generators_[i].reset(MakeGenerator(descriptor->field(i), options));
}
}
FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
const Options& options) {
if (field->is_repeated()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new RepeatedMessageFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // RepeatedStringFieldGenerator handles unknown ctypes.
case FieldOptions::STRING:
return new RepeatedStringFieldGenerator(field, options);
}
case FieldDescriptor::CPPTYPE_ENUM:
return new RepeatedEnumFieldGenerator(field, options);
default:
return new RepeatedPrimitiveFieldGenerator(field, options);
}
} else if (field->containing_oneof()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageOneofFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringOneofFieldGenerator handles unknown ctypes.
case FieldOptions::STRING:
return new StringOneofFieldGenerator(field, options);
}
case FieldDescriptor::CPPTYPE_ENUM:
return new EnumOneofFieldGenerator(field, options);
default:
return new PrimitiveOneofFieldGenerator(field, options);
}
} else {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringFieldGenerator handles unknown ctypes.
case FieldOptions::STRING:
return new StringFieldGenerator(field, options);
}
case FieldDescriptor::CPPTYPE_ENUM:
return new EnumFieldGenerator(field, options);
default:
return new PrimitiveFieldGenerator(field, options);
}
}
}
FieldGeneratorMap::~FieldGeneratorMap() {}
const FieldGenerator& FieldGeneratorMap::get(
const FieldDescriptor* field) const {
GOOGLE_CHECK_EQ(field->containing_type(), descriptor_);
return *field_generators_[field->index()];
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,185 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
#include <map>
#include <memory>
#include <string>
#include <google/protobuf/descriptor.h>
#include "google/protobuf/compiler/cpp/cpp_options.h"
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace cpp {
// Helper function: set variables in the map that are the same for all
// field code generators.
// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size',
// 'deprecation'].
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options);
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
map<string, string>* variables);
class FieldGenerator {
public:
FieldGenerator() {}
virtual ~FieldGenerator();
// Generate lines of code declaring members fields of the message class
// needed to represent this field. These are placed inside the message
// class.
virtual void GeneratePrivateMembers(io::Printer* printer) const = 0;
// Generate static default variable for this field. These are placed inside
// the message class. Most field types don't need this, so the default
// implementation is empty.
virtual void GenerateStaticMembers(io::Printer* printer) const {}
// Generate prototypes for all of the accessor functions related to this
// field. These are placed inside the class definition.
virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0;
// Generate inline definitions of accessor functions for this field.
// These are placed inside the header after all class definitions.
virtual void GenerateInlineAccessorDefinitions(
io::Printer* printer) const = 0;
// Generate definitions of accessors that aren't inlined. These are
// placed somewhere in the .cc file.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {}
// Generate lines of code (statements, not declarations) which clear the
// field. This is used to define the clear_$name$() method as well as
// the Clear() method for the whole message.
virtual void GenerateClearingCode(io::Printer* printer) const = 0;
// Generate lines of code (statements, not declarations) which merges the
// contents of the field from the current message to the target message,
// which is stored in the generated code variable "from".
// This is used to fill in the MergeFrom method for the whole message.
// Details of this usage can be found in message.cc under the
// GenerateMergeFrom method.
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
// Generate lines of code (statements, not declarations) which swaps
// this field and the corresponding field of another message, which
// is stored in the generated code variable "other". This is used to
// define the Swap method. Details of usage can be found in
// message.cc under the GenerateSwap method.
virtual void GenerateSwappingCode(io::Printer* printer) const = 0;
// Generate initialization code for private members declared by
// GeneratePrivateMembers(). These go into the message class's SharedCtor()
// method, invoked by each of the generated constructors.
virtual void GenerateConstructorCode(io::Printer* printer) const = 0;
// Generate any code that needs to go in the class's SharedDtor() method,
// invoked by the destructor.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateDestructorCode(io::Printer* printer) const {}
// Generate code that allocates the fields's default instance.
virtual void GenerateDefaultInstanceAllocator(io::Printer* printer) const {}
// Generate code that should be run when ShutdownProtobufLibrary() is called,
// to delete all dynamically-allocated objects.
virtual void GenerateShutdownCode(io::Printer* printer) const {}
// Generate lines to decode this field, which will be placed inside the
// message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
// Generate lines to decode this field from a packed value, which will be
// placed inside the message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
const;
// Generate lines to serialize this field, which are placed within the
// message's SerializeWithCachedSizes() method.
virtual void GenerateSerializeWithCachedSizes(io::Printer* printer) const = 0;
// Generate lines to serialize this field directly to the array "target",
// which are placed within the message's SerializeWithCachedSizesToArray()
// method. This must also advance "target" past the written bytes.
virtual void GenerateSerializeWithCachedSizesToArray(
io::Printer* printer) const = 0;
// Generate lines to compute the serialized size of this field, which
// are placed in the message's ByteSize() method.
virtual void GenerateByteSize(io::Printer* printer) const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
};
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
explicit FieldGeneratorMap(const Descriptor* descriptor, const Options& options);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
private:
const Descriptor* descriptor_;
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
const Options& options);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
@@ -0,0 +1,494 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <limits>
#include <map>
#include <vector>
#include <google/protobuf/stubs/hash.h>
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/common.h>
#include "google/protobuf/stubs/strutil.h"
#include <google/protobuf/stubs/substitute.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
string DotsToUnderscores(const string& name) {
return StringReplace(name, ".", "_", true);
}
string DotsToColons(const string& name) {
return StringReplace(name, ".", "::", true);
}
const char* const kKeywordList[] = {
"and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case",
"catch", "char", "class", "compl", "const", "const_cast", "continue",
"default", "delete", "do", "double", "dynamic_cast", "else", "enum",
"explicit", "extern", "false", "float", "for", "friend", "goto", "if",
"inline", "int", "long", "mutable", "namespace", "new", "not", "not_eq",
"operator", "or", "or_eq", "private", "protected", "public", "register",
"reinterpret_cast", "return", "short", "signed", "sizeof", "static",
"static_cast", "struct", "switch", "template", "this", "throw", "true", "try",
"typedef", "typeid", "typename", "union", "unsigned", "using", "virtual",
"void", "volatile", "wchar_t", "while", "xor", "xor_eq"
};
hash_set<string> MakeKeywordsMap() {
hash_set<string> result;
for (int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) {
result.insert(kKeywordList[i]);
}
return result;
}
hash_set<string> kKeywords = MakeKeywordsMap();
// Returns whether the provided descriptor has an extension. This includes its
// nested types.
bool HasExtension(const Descriptor* descriptor) {
if (descriptor->extension_count() > 0) {
return true;
}
for (int i = 0; i < descriptor->nested_type_count(); ++i) {
if (HasExtension(descriptor->nested_type(i))) {
return true;
}
}
return false;
}
} // namespace
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
string result;
// Note: I distrust ctype.h due to locales.
for (int i = 0; i < input.size(); i++) {
if ('a' <= input[i] && input[i] <= 'z') {
if (cap_next_letter) {
result += input[i] + ('A' - 'a');
} else {
result += input[i];
}
cap_next_letter = false;
} else if ('A' <= input[i] && input[i] <= 'Z') {
// Capital letters are left as-is.
result += input[i];
cap_next_letter = false;
} else if ('0' <= input[i] && input[i] <= '9') {
result += input[i];
cap_next_letter = true;
} else {
cap_next_letter = true;
}
}
return result;
}
const char kThickSeparator[] =
"// ===================================================================\n";
const char kThinSeparator[] =
"// -------------------------------------------------------------------\n";
string ClassName(const Descriptor* descriptor, bool qualified) {
// Find "outer", the descriptor of the top-level message in which
// "descriptor" is embedded.
const Descriptor* outer = descriptor;
while (outer->containing_type() != NULL) outer = outer->containing_type();
const string& outer_name = outer->full_name();
string inner_name = descriptor->full_name().substr(outer_name.size());
if (qualified) {
return "::" + DotsToColons(outer_name) + DotsToUnderscores(inner_name);
} else {
return outer->name() + DotsToUnderscores(inner_name);
}
}
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified) {
if (enum_descriptor->containing_type() == NULL) {
if (qualified) {
return "::" + DotsToColons(enum_descriptor->full_name());
} else {
return enum_descriptor->name();
}
} else {
string result = ClassName(enum_descriptor->containing_type(), qualified);
result += '_';
result += enum_descriptor->name();
return result;
}
}
string SuperClassName(const Descriptor* descriptor) {
return HasDescriptorMethods(descriptor->file()) ?
"::google::protobuf::Message" : "::google::protobuf::MessageLite";
}
string FieldName(const FieldDescriptor* field) {
string result = field->name();
LowerString(&result);
if (kKeywords.count(result) > 0) {
result.append("_");
}
return result;
}
string FieldConstantName(const FieldDescriptor *field) {
string field_name = UnderscoresToCamelCase(field->name(), true);
string result = "k" + field_name + "FieldNumber";
if (!field->is_extension() &&
field->containing_type()->FindFieldByCamelcaseName(
field->camelcase_name()) != field) {
// This field's camelcase name is not unique. As a hack, add the field
// number to the constant name. This makes the constant rather useless,
// but what can we do?
result += "_" + SimpleItoa(field->number());
}
return result;
}
string FieldMessageTypeName(const FieldDescriptor* field) {
// Note: The Google-internal version of Protocol Buffers uses this function
// as a hook point for hacks to support legacy code.
return ClassName(field->message_type(), true);
}
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
return StripSuffixString(filename, ".proto");
}
}
const char* PrimitiveTypeName(FieldDescriptor::CppType type) {
switch (type) {
case FieldDescriptor::CPPTYPE_INT32 : return "::google::protobuf::int32";
case FieldDescriptor::CPPTYPE_INT64 : return "::google::protobuf::int64";
case FieldDescriptor::CPPTYPE_UINT32 : return "::google::protobuf::uint32";
case FieldDescriptor::CPPTYPE_UINT64 : return "::google::protobuf::uint64";
case FieldDescriptor::CPPTYPE_DOUBLE : return "double";
case FieldDescriptor::CPPTYPE_FLOAT : return "float";
case FieldDescriptor::CPPTYPE_BOOL : return "bool";
case FieldDescriptor::CPPTYPE_ENUM : return "int";
case FieldDescriptor::CPPTYPE_STRING : return "::std::string";
case FieldDescriptor::CPPTYPE_MESSAGE: return NULL;
// No default because we want the compiler to complain if any new
// CppTypes are added.
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return NULL;
}
const char* DeclaredTypeMethodName(FieldDescriptor::Type type) {
switch (type) {
case FieldDescriptor::TYPE_INT32 : return "Int32";
case FieldDescriptor::TYPE_INT64 : return "Int64";
case FieldDescriptor::TYPE_UINT32 : return "UInt32";
case FieldDescriptor::TYPE_UINT64 : return "UInt64";
case FieldDescriptor::TYPE_SINT32 : return "SInt32";
case FieldDescriptor::TYPE_SINT64 : return "SInt64";
case FieldDescriptor::TYPE_FIXED32 : return "Fixed32";
case FieldDescriptor::TYPE_FIXED64 : return "Fixed64";
case FieldDescriptor::TYPE_SFIXED32: return "SFixed32";
case FieldDescriptor::TYPE_SFIXED64: return "SFixed64";
case FieldDescriptor::TYPE_FLOAT : return "Float";
case FieldDescriptor::TYPE_DOUBLE : return "Double";
case FieldDescriptor::TYPE_BOOL : return "Bool";
case FieldDescriptor::TYPE_ENUM : return "Enum";
case FieldDescriptor::TYPE_STRING : return "String";
case FieldDescriptor::TYPE_BYTES : return "Bytes";
case FieldDescriptor::TYPE_GROUP : return "Group";
case FieldDescriptor::TYPE_MESSAGE : return "Message";
// No default because we want the compiler to complain if any new
// types are added.
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return "";
}
string Int32ToString(int number) {
// gcc rejects the decimal form of kint32min.
if (number == kint32min) {
GOOGLE_COMPILE_ASSERT(kint32min == (~0x7fffffff), kint32min_value_error);
return "(~0x7fffffff)";
} else {
return SimpleItoa(number);
}
}
string Int64ToString(int64 number) {
// gcc rejects the decimal form of kint64min
if (number == kint64min) {
// Make sure we are in a 2's complement system.
GOOGLE_COMPILE_ASSERT(kint64min == GOOGLE_LONGLONG(~0x7fffffffffffffff),
kint64min_value_error);
return "GOOGLE_LONGLONG(~0x7fffffffffffffff)";
}
return "GOOGLE_LONGLONG(" + SimpleItoa(number) + ")";
}
string DefaultValue(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return Int32ToString(field->default_value_int32());
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(field->default_value_uint32()) + "u";
case FieldDescriptor::CPPTYPE_INT64:
return Int64ToString(field->default_value_int64());
case FieldDescriptor::CPPTYPE_UINT64:
return "GOOGLE_ULONGLONG(" + SimpleItoa(field->default_value_uint64())+ ")";
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value = field->default_value_double();
if (value == numeric_limits<double>::infinity()) {
return "::google::protobuf::internal::Infinity()";
} else if (value == -numeric_limits<double>::infinity()) {
return "-::google::protobuf::internal::Infinity()";
} else if (value != value) {
return "::google::protobuf::internal::NaN()";
} else {
return SimpleDtoa(value);
}
}
case FieldDescriptor::CPPTYPE_FLOAT:
{
float value = field->default_value_float();
if (value == numeric_limits<float>::infinity()) {
return "static_cast<float>(::google::protobuf::internal::Infinity())";
} else if (value == -numeric_limits<float>::infinity()) {
return "static_cast<float>(-::google::protobuf::internal::Infinity())";
} else if (value != value) {
return "static_cast<float>(::google::protobuf::internal::NaN())";
} else {
string float_value = SimpleFtoa(value);
// If floating point value contains a period (.) or an exponent
// (either E or e), then append suffix 'f' to make it a float
// literal.
if (float_value.find_first_of(".eE") != string::npos) {
float_value.push_back('f');
}
return float_value;
}
}
case FieldDescriptor::CPPTYPE_BOOL:
return field->default_value_bool() ? "true" : "false";
case FieldDescriptor::CPPTYPE_ENUM:
// Lazy: Generate a static_cast because we don't have a helper function
// that constructs the full name of an enum value.
return strings::Substitute(
"static_cast< $0 >($1)",
ClassName(field->enum_type(), true),
Int32ToString(field->default_value_enum()->number()));
case FieldDescriptor::CPPTYPE_STRING:
return "\"" + EscapeTrigraphs(
CEscape(field->default_value_string())) +
"\"";
case FieldDescriptor::CPPTYPE_MESSAGE:
return FieldMessageTypeName(field) + "::default_instance()";
}
// Can't actually get here; make compiler happy. (We could add a default
// case above but then we wouldn't get the nice compiler warning when a
// new type is added.)
GOOGLE_LOG(FATAL) << "Can't get here.";
return "";
}
// Convert a file name into a valid identifier.
string FilenameIdentifier(const string& filename) {
string result;
for (int i = 0; i < filename.size(); i++) {
if (ascii_isalnum(filename[i])) {
result.push_back(filename[i]);
} else {
// Not alphanumeric. To avoid any possibility of name conflicts we
// use the hex code for the character.
result.push_back('_');
char buffer[kFastToBufferSize];
result.append(FastHexToBuffer(static_cast<uint8>(filename[i]), buffer));
}
}
return result;
}
// Return the name of the AddDescriptors() function for a given file.
string GlobalAddDescriptorsName(const string& filename) {
return "protobuf_AddDesc_" + FilenameIdentifier(filename);
}
// Return the name of the AssignDescriptors() function for a given file.
string GlobalAssignDescriptorsName(const string& filename) {
return "protobuf_AssignDesc_" + FilenameIdentifier(filename);
}
// Return the name of the ShutdownFile() function for a given file.
string GlobalShutdownFileName(const string& filename) {
return "protobuf_ShutdownFile_" + FilenameIdentifier(filename);
}
// Return the qualified C++ name for a file level symbol.
string QualifiedFileLevelSymbol(const string& package, const string& name) {
if (package.empty()) {
return StrCat("::", name);
}
return StrCat("::", DotsToColons(package), "::", name);
}
// Escape C++ trigraphs by escaping question marks to \?
string EscapeTrigraphs(const string& to_escape) {
return StringReplace(to_escape, "?", "\\?", true);
}
// Escaped function name to eliminate naming conflict.
string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const string& prefix) {
// Do not use FieldName() since it will escape keywords.
string name = field->name();
LowerString(&name);
string function_name = prefix + name;
if (descriptor->FindFieldByName(function_name)) {
// Single underscore will also make it conflicting with the private data
// member. We use double underscore to escape function names.
function_name.append("__");
} else if (kKeywords.count(name) > 0) {
// If the field name is a keyword, we append the underscore back to keep it
// consistent with other function names.
function_name.append("_");
}
return function_name;
}
bool StaticInitializersForced(const FileDescriptor* file) {
if (HasDescriptorMethods(file) || file->extension_count() > 0) {
return true;
}
for (int i = 0; i < file->message_type_count(); ++i) {
if (HasExtension(file->message_type(i))) {
return true;
}
}
return false;
}
void PrintHandlingOptionalStaticInitializers(
const FileDescriptor* file, io::Printer* printer,
const char* with_static_init, const char* without_static_init,
const char* var1, const string& val1,
const char* var2, const string& val2) {
map<string, string> vars;
if (var1) {
vars[var1] = val1;
}
if (var2) {
vars[var2] = val2;
}
PrintHandlingOptionalStaticInitializers(
vars, file, printer, with_static_init, without_static_init);
}
void PrintHandlingOptionalStaticInitializers(
const map<string, string>& vars, const FileDescriptor* file,
io::Printer* printer, const char* with_static_init,
const char* without_static_init) {
if (StaticInitializersForced(file)) {
printer->Print(vars, with_static_init);
} else {
printer->Print(vars, (string(
"#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n") +
without_static_init +
"#else\n" +
with_static_init +
"#endif\n").c_str());
}
}
static bool HasEnumDefinitions(const Descriptor* message_type) {
if (message_type->enum_type_count() > 0) return true;
for (int i = 0; i < message_type->nested_type_count(); ++i) {
if (HasEnumDefinitions(message_type->nested_type(i))) return true;
}
return false;
}
bool HasEnumDefinitions(const FileDescriptor* file) {
if (file->enum_type_count() > 0) return true;
for (int i = 0; i < file->message_type_count(); ++i) {
if (HasEnumDefinitions(file->message_type(i))) return true;
}
return false;
}
bool IsStringOrMessage(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT32:
case FieldDescriptor::CPPTYPE_UINT64:
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_FLOAT:
case FieldDescriptor::CPPTYPE_BOOL:
case FieldDescriptor::CPPTYPE_ENUM:
return false;
case FieldDescriptor::CPPTYPE_STRING:
case FieldDescriptor::CPPTYPE_MESSAGE:
return true;
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return false;
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,206 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
#include <map>
#include <string>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
namespace google {
namespace protobuf {
namespace io {
class Printer;
}
namespace compiler {
namespace cpp {
// Commonly-used separator comments. Thick is a line of '=', thin is a line
// of '-'.
extern const char kThickSeparator[];
extern const char kThinSeparator[];
// Returns the non-nested type name for the given type. If "qualified" is
// true, prefix the type with the full namespace. For example, if you had:
// package foo.bar;
// message Baz { message Qux {} }
// Then the qualified ClassName for Qux would be:
// ::foo::bar::Baz_Qux
// While the non-qualified version would be:
// Baz_Qux
string ClassName(const Descriptor* descriptor, bool qualified);
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified);
string SuperClassName(const Descriptor* descriptor);
// Get the (unqualified) name that should be used for this field in C++ code.
// The name is coerced to lower-case to emulate proto1 behavior. People
// should be using lowercase-with-underscores style for proto field names
// anyway, so normally this just returns field->name().
string FieldName(const FieldDescriptor* field);
// Get the unqualified name that should be used for a field's field
// number constant.
string FieldConstantName(const FieldDescriptor *field);
// Returns the scope where the field was defined (for extensions, this is
// different from the message type to which the field applies).
inline const Descriptor* FieldScope(const FieldDescriptor* field) {
return field->is_extension() ?
field->extension_scope() : field->containing_type();
}
// Returns the fully-qualified type name field->message_type(). Usually this
// is just ClassName(field->message_type(), true);
string FieldMessageTypeName(const FieldDescriptor* field);
// Strips ".proto" or ".protodevel" from the end of a filename.
string StripProto(const string& filename);
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
// Note: non-built-in type names will be qualified, meaning they will start
// with a ::. If you are using the type as a template parameter, you will
// need to insure there is a space between the < and the ::, because the
// ridiculous C++ standard defines "<:" to be a synonym for "[".
const char* PrimitiveTypeName(FieldDescriptor::CppType type);
// Get the declared type name in CamelCase format, as is used e.g. for the
// methods of WireFormat. For example, TYPE_INT32 becomes "Int32".
const char* DeclaredTypeMethodName(FieldDescriptor::Type type);
// Return the code that evaluates to the number when compiled.
string Int32ToString(int number);
// Return the code that evaluates to the number when compiled.
string Int64ToString(int64 number);
// Get code that evaluates to the field's default value.
string DefaultValue(const FieldDescriptor* field);
// Convert a file name into a valid identifier.
string FilenameIdentifier(const string& filename);
// Return the name of the AddDescriptors() function for a given file.
string GlobalAddDescriptorsName(const string& filename);
// Return the name of the AssignDescriptors() function for a given file.
string GlobalAssignDescriptorsName(const string& filename);
// Return the qualified C++ name for a file level symbol.
string QualifiedFileLevelSymbol(const string& package, const string& name);
// Return the name of the ShutdownFile() function for a given file.
string GlobalShutdownFileName(const string& filename);
// Escape C++ trigraphs by escaping question marks to \?
string EscapeTrigraphs(const string& to_escape);
// Escaped function name to eliminate naming conflict.
string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const string& prefix);
// Do message classes in this file use UnknownFieldSet?
// Otherwise, messages will store unknown fields in a string
inline bool UseUnknownFieldSet(const FileDescriptor* file) {
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
}
// Does this file have any enum type definitions?
bool HasEnumDefinitions(const FileDescriptor* file);
// Does this file have generated parsing, serialization, and other
// standard methods for which reflection-based fallback implementations exist?
inline bool HasGeneratedMethods(const FileDescriptor* file) {
return file->options().optimize_for() != FileOptions::CODE_SIZE;
}
// Do message classes in this file have descriptor and reflection methods?
inline bool HasDescriptorMethods(const FileDescriptor* file) {
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
}
// Should we generate generic services for this file?
inline bool HasGenericServices(const FileDescriptor* file) {
return file->service_count() > 0 &&
file->options().optimize_for() != FileOptions::LITE_RUNTIME &&
file->options().cc_generic_services();
}
// Should string fields in this file verify that their contents are UTF-8?
inline bool HasUtf8Verification(const FileDescriptor* file) {
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
}
// Should we generate a separate, super-optimized code path for serializing to
// flat arrays? We don't do this in Lite mode because we'd rather reduce code
// size.
inline bool HasFastArraySerialization(const FileDescriptor* file) {
return file->options().optimize_for() == FileOptions::SPEED;
}
// Returns whether we have to generate code with static initializers.
bool StaticInitializersForced(const FileDescriptor* file);
// Prints 'with_static_init' if static initializers have to be used for the
// provided file. Otherwise emits both 'with_static_init' and
// 'without_static_init' using #ifdef.
void PrintHandlingOptionalStaticInitializers(
const FileDescriptor* file, io::Printer* printer,
const char* with_static_init, const char* without_static_init,
const char* var1 = NULL, const string& val1 = "",
const char* var2 = NULL, const string& val2 = "");
void PrintHandlingOptionalStaticInitializers(
const map<string, string>& vars, const FileDescriptor* file,
io::Printer* printer, const char* with_static_init,
const char* without_static_init);
// Returns true if the field's CPPTYPE is string or message.
bool IsStringOrMessage(const FieldDescriptor* field);
string UnderscoresToCamelCase(const string& input, bool cap_next_letter);
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,175 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
#include <memory>
#include <string>
#include <vector>
#include "google/protobuf/compiler/cpp/cpp_field.h"
#include "google/protobuf/compiler/cpp/cpp_options.h"
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace cpp {
class EnumGenerator; // enum.h
class ExtensionGenerator; // extension.h
class MessageGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit MessageGenerator(const Descriptor* descriptor,
const Options& options);
~MessageGenerator();
// Header stuff.
// Generate foward declarations for this class and all its nested types.
void GenerateForwardDeclaration(io::Printer* printer);
// Generate definitions of all nested enums (must come before class
// definitions because those classes use the enums definitions).
void GenerateEnumDefinitions(io::Printer* printer);
// Generate specializations of GetEnumDescriptor<MyEnum>().
// Precondition: in ::google::protobuf namespace.
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
// Generate definitions for this class and all its nested types.
void GenerateClassDefinition(io::Printer* printer);
// Generate definitions of inline methods (placed at the end of the header
// file).
void GenerateInlineMethods(io::Printer* printer);
// Source file stuff.
// Generate code which declares all the global descriptor pointers which
// will be initialized by the methods below.
void GenerateDescriptorDeclarations(io::Printer* printer);
// Generate code that initializes the global variable storing the message's
// descriptor.
void GenerateDescriptorInitializer(io::Printer* printer, int index);
// Generate code that calls MessageFactory::InternalRegisterGeneratedMessage()
// for all types.
void GenerateTypeRegistrations(io::Printer* printer);
// Generates code that allocates the message's default instance.
void GenerateDefaultInstanceAllocator(io::Printer* printer);
// Generates code that initializes the message's default instance. This
// is separate from allocating because all default instances must be
// allocated before any can be initialized.
void GenerateDefaultInstanceInitializer(io::Printer* printer);
// Generates code that should be run when ShutdownProtobufLibrary() is called,
// to delete all dynamically-allocated objects.
void GenerateShutdownCode(io::Printer* printer);
// Generate all non-inline methods for this class.
void GenerateClassMethods(io::Printer* printer);
private:
// Generate declarations and definitions of accessors for fields.
void GenerateFieldAccessorDeclarations(io::Printer* printer);
void GenerateFieldAccessorDefinitions(io::Printer* printer);
// Generate the field offsets array.
void GenerateOffsets(io::Printer* printer);
// Generate constructors and destructor.
void GenerateStructors(io::Printer* printer);
// The compiler typically generates multiple copies of each constructor and
// destructor: http://gcc.gnu.org/bugs.html#nonbugs_cxx
// Placing common code in a separate method reduces the generated code size.
//
// Generate the shared constructor code.
void GenerateSharedConstructorCode(io::Printer* printer);
// Generate the shared destructor code.
void GenerateSharedDestructorCode(io::Printer* printer);
// Generate standard Message methods.
void GenerateClear(io::Printer* printer);
void GenerateOneofClear(io::Printer* printer);
void GenerateMergeFromCodedStream(io::Printer* printer);
void GenerateSerializeWithCachedSizes(io::Printer* printer);
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer);
void GenerateSerializeWithCachedSizesBody(io::Printer* printer,
bool to_array);
void GenerateByteSize(io::Printer* printer);
void GenerateMergeFrom(io::Printer* printer);
void GenerateCopyFrom(io::Printer* printer);
void GenerateSwap(io::Printer* printer);
void GenerateIsInitialized(io::Printer* printer);
// Helpers for GenerateSerializeWithCachedSizes().
void GenerateSerializeOneField(io::Printer* printer,
const FieldDescriptor* field,
bool unbounded);
void GenerateSerializeOneExtensionRange(
io::Printer* printer, const Descriptor::ExtensionRange* range,
bool unbounded);
const Descriptor* descriptor_;
string classname_;
Options options_;
FieldGeneratorMap field_generators_;
vector< vector<string> > runs_of_fields_; // that might be trivially cleared
scoped_array<scoped_ptr<MessageGenerator> > nested_generators_;
scoped_array<scoped_ptr<EnumGenerator> > enum_generators_;
scoped_array<scoped_ptr<ExtensionGenerator> > extension_generators_;
bool uses_string_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
@@ -0,0 +1,375 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_message_field.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
void SetMessageVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = FieldMessageTypeName(descriptor);
(*variables)["stream_writer"] = (*variables)["declared_type"] +
(HasFastArraySerialization(descriptor->message_type()->file()) ?
"MaybeToArray" :
"");
// NOTE: Escaped here to unblock proto1->proto2 migration.
// TODO(liujisi): Extend this to apply for other conflicting methods.
(*variables)["release_name"] =
SafeFunctionName(descriptor->containing_type(),
descriptor, "release_");
(*variables)["full_name"] = descriptor->full_name();
}
} // namespace
// ===================================================================
MessageFieldGenerator::
MessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetMessageVariables(descriptor, &variables_, options);
}
MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_, "$type$* $name$_;\n");
}
void MessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline const $type$& $name$() const$deprecation$;\n"
"inline $type$* mutable_$name$()$deprecation$;\n"
"inline $type$* $release_name$()$deprecation$;\n"
"inline void set_allocated_$name$($type$* $name$)$deprecation$;\n");
}
void MessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const $type$& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n");
PrintHandlingOptionalStaticInitializers(
variables_, descriptor_->file(), printer,
// With static initializers.
" return $name$_ != NULL ? *$name$_ : *default_instance_->$name$_;\n",
// Without.
" return $name$_ != NULL ? *$name$_ : *default_instance().$name$_;\n");
printer->Print(variables_,
"}\n"
"inline $type$* $classname$::mutable_$name$() {\n"
" set_has_$name$();\n"
" if ($name$_ == NULL) $name$_ = new $type$;\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline $type$* $classname$::$release_name$() {\n"
" clear_has_$name$();\n"
" $type$* temp = $name$_;\n"
" $name$_ = NULL;\n"
" return temp;\n"
"}\n"
"inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
" delete $name$_;\n"
" $name$_ = $name$;\n"
" if ($name$) {\n"
" set_has_$name$();\n"
" } else {\n"
" clear_has_$name$();\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
void MessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($name$_ != NULL) $name$_->$type$::Clear();\n");
}
void MessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_,
"mutable_$name$()->$type$::MergeFrom(from.$name$());\n");
}
void MessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
}
void MessageFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = NULL;\n");
}
void MessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n"
" input, mutable_$name$()));\n");
} else {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::ReadGroupNoVirtual(\n"
" $number$, input, mutable_$name$()));\n");
}
}
void MessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
" $number$, this->$name$(), output);\n");
}
void MessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$NoVirtualToArray(\n"
" $number$, this->$name$(), target);\n");
}
void MessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$SizeNoVirtual(\n"
" this->$name$());\n");
}
// ===================================================================
MessageOneofFieldGenerator::
MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: MessageFieldGenerator(descriptor, options) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {}
void MessageOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const $type$& $classname$::$name$() const {\n"
" return has_$name$() ? *$oneof_prefix$$name$_\n"
" : $type$::default_instance();\n"
"}\n"
"inline $type$* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = new $type$;\n"
" }\n"
" return $oneof_prefix$$name$_;\n"
"}\n"
"inline $type$* $classname$::$release_name$() {\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" $type$* temp = $oneof_prefix$$name$_;\n"
" $oneof_prefix$$name$_ = NULL;\n"
" return temp;\n"
" } else {\n"
" return NULL;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
" clear_$oneof_name$();\n"
" if ($name$) {\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = $name$;\n"
" }\n"
"}\n");
}
void MessageOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
// if it is the active field, it cannot be NULL.
printer->Print(variables_,
"delete $oneof_prefix$$name$_;\n");
}
void MessageOneofFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
// Don't print any swapping code. Swapping the union will swap this field.
}
void MessageOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
// Don't print any constructor code. The field is in a union. We allocate
// space only when this field is used.
}
// ===================================================================
RepeatedMessageFieldGenerator::
RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetMessageVariables(descriptor, &variables_, options);
}
RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
void RepeatedMessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::RepeatedPtrField< $type$ > $name$_;\n");
}
void RepeatedMessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline const $type$& $name$(int index) const$deprecation$;\n"
"inline $type$* mutable_$name$(int index)$deprecation$;\n"
"inline $type$* add_$name$()$deprecation$;\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
" $name$() const$deprecation$;\n"
"inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
" mutable_$name$()$deprecation$;\n");
}
void RepeatedMessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const $type$& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n"
"inline $type$* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
"inline $type$* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
" return $name$_.Add();\n"
"}\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
"}\n");
}
void RepeatedMessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Clear();\n");
}
void RepeatedMessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedMessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
}
void RepeatedMessageFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
// Not needed for repeated fields.
}
void RepeatedMessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n"
" input, add_$name$()));\n");
} else {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::ReadGroupNoVirtual(\n"
" $number$, input, add_$name$()));\n");
}
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" ::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
" $number$, this->$name$(i), output);\n"
"}\n");
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$NoVirtualToArray(\n"
" $number$, this->$name$(i), target);\n"
"}\n");
}
void RepeatedMessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ * this->$name$_size();\n"
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" total_size +=\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$SizeNoVirtual(\n"
" this->$name$(i));\n"
"}\n");
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,121 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
#include <map>
#include <string>
#include "google/protobuf/compiler/cpp/cpp_field.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
class MessageFieldGenerator : public FieldGenerator {
public:
explicit MessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~MessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
protected:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
};
class MessageOneofFieldGenerator : public MessageFieldGenerator {
public:
explicit MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator);
};
class RepeatedMessageFieldGenerator : public FieldGenerator {
public:
explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~RepeatedMessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
@@ -0,0 +1,58 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: rennie@google.com (Jeffrey Rennie)
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__
#include <string>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
// Generator options:
struct Options {
Options() : safe_boundary_check(false) {
}
string dllexport_decl;
bool safe_boundary_check;
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__
@@ -0,0 +1,453 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_primitive_field.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
using internal::WireFormatLite;
namespace {
// For encodings with fixed sizes, returns that size in bytes. Otherwise
// returns -1.
int FixedSize(FieldDescriptor::Type type) {
switch (type) {
case FieldDescriptor::TYPE_INT32 : return -1;
case FieldDescriptor::TYPE_INT64 : return -1;
case FieldDescriptor::TYPE_UINT32 : return -1;
case FieldDescriptor::TYPE_UINT64 : return -1;
case FieldDescriptor::TYPE_SINT32 : return -1;
case FieldDescriptor::TYPE_SINT64 : return -1;
case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size;
case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size;
case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size;
case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size;
case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize;
case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize;
case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize;
case FieldDescriptor::TYPE_ENUM : return -1;
case FieldDescriptor::TYPE_STRING : return -1;
case FieldDescriptor::TYPE_BYTES : return -1;
case FieldDescriptor::TYPE_GROUP : return -1;
case FieldDescriptor::TYPE_MESSAGE : return -1;
// No default because we want the compiler to complain if any new
// types are added.
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return -1;
}
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type());
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
int fixed_size = FixedSize(descriptor->type());
if (fixed_size != -1) {
(*variables)["fixed_size"] = SimpleItoa(fixed_size);
}
(*variables)["wire_format_field_type"] =
"::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name(
static_cast<FieldDescriptorProto_Type>(descriptor->type()));
(*variables)["full_name"] = descriptor->full_name();
}
} // namespace
// ===================================================================
PrimitiveFieldGenerator::
PrimitiveFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetPrimitiveVariables(descriptor, &variables_, options);
}
PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}
void PrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_, "$type$ $name$_;\n");
}
void PrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $name$() const$deprecation$;\n"
"inline void set_$name$($type$ value)$deprecation$;\n");
}
void PrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" set_has_$name$();\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void PrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $default$;\n");
}
void PrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "set_$name$(from.$name$());\n");
}
void PrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
}
void PrimitiveFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_ = $default$;\n");
}
void PrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" $type$, $wire_format_field_type$>(\n"
" input, &$name$_)));\n"
"set_has_$name$();\n");
}
void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$declared_type$("
"$number$, this->$name$(), output);\n");
}
void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray("
"$number$, this->$name$(), target);\n");
}
void PrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" this->$name$());\n");
} else {
printer->Print(variables_,
"total_size += $tag_size$ + $fixed_size$;\n");
}
}
// ===================================================================
PrimitiveOneofFieldGenerator::
PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: PrimitiveFieldGenerator(descriptor, options) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
void PrimitiveOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_;\n"
" }\n"
" return $default$;\n"
"}\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
" $oneof_prefix$$name$_ = value;\n"
"}\n");
}
void PrimitiveOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
// Don't print any swapping code. Swapping the union will swap this field.
}
void PrimitiveOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(
variables_,
" $classname$_default_oneof_instance_->$name$_ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"clear_$oneof_name$();\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" $type$, $wire_format_field_type$>(\n"
" input, &$oneof_prefix$$name$_)));\n"
"set_has_$name$();\n");
}
// ===================================================================
RepeatedPrimitiveFieldGenerator::
RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetPrimitiveVariables(descriptor, &variables_, options);
if (descriptor->options().packed()) {
variables_["packed_reader"] = "ReadPackedPrimitive";
variables_["repeated_reader"] = "ReadRepeatedPrimitiveNoInline";
} else {
variables_["packed_reader"] = "ReadPackedPrimitiveNoInline";
variables_["repeated_reader"] = "ReadRepeatedPrimitive";
}
}
RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}
void RepeatedPrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::RepeatedField< $type$ > $name$_;\n");
if (descriptor_->options().packed() && HasGeneratedMethods(descriptor_->file())) {
printer->Print(variables_,
"mutable int _$name$_cached_byte_size_;\n");
}
}
void RepeatedPrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $name$(int index) const$deprecation$;\n"
"inline void set_$name$(int index, $type$ value)$deprecation$;\n"
"inline void add_$name$($type$ value)$deprecation$;\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedField< $type$ >&\n"
" $name$() const$deprecation$;\n"
"inline ::google::protobuf::RepeatedField< $type$ >*\n"
" mutable_$name$()$deprecation$;\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get(index);\n"
"}\n"
"inline void $classname$::set_$name$(int index, $type$ value) {\n"
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"inline void $classname$::add_$name$($type$ value) {\n"
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::google::protobuf::RepeatedField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
"}\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Clear();\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
if (descriptor_->options().packed()) {
printer->Print(variables_, "_$name$_cached_byte_size_ = 0;\n");
}
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n"
" $type$, $wire_format_field_type$>(\n"
" $tag_size$, $tag$, input, this->mutable_$name$())));\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
printer->Print(variables_,
"DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n"
" $type$, $wire_format_field_type$>(\n"
" input, this->mutable_$name$())));\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->options().packed()) {
// Write the tag and the size.
printer->Print(variables_,
"if (this->$name$_size() > 0) {\n"
" ::google::protobuf::internal::WireFormatLite::WriteTag("
"$number$, "
"::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
"output);\n"
" output->WriteVarint32(_$name$_cached_byte_size_);\n"
"}\n");
}
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n"
" this->$name$(i), output);\n");
} else {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
" $number$, this->$name$(i), output);\n");
}
printer->Print("}\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (descriptor_->options().packed()) {
// Write the tag and the size.
printer->Print(variables_,
"if (this->$name$_size() > 0) {\n"
" target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n"
" $number$,\n"
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n"
" _$name$_cached_byte_size_, target);\n"
"}\n");
}
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
" target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$NoTagToArray(this->$name$(i), target);\n");
} else {
printer->Print(variables_,
" target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$ToArray($number$, this->$name$(i), target);\n");
}
printer->Print("}\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
" int data_size = 0;\n");
printer->Indent();
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::\n"
" $declared_type$Size(this->$name$(i));\n"
"}\n");
} else {
printer->Print(variables_,
"data_size = $fixed_size$ * this->$name$_size();\n");
}
if (descriptor_->options().packed()) {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
"}\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
"_$name$_cached_byte_size_ = data_size;\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
"total_size += data_size;\n");
} else {
printer->Print(variables_,
"total_size += $tag_size$ * this->$name$_size() + data_size;\n");
}
printer->Outdent();
printer->Print("}\n");
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,123 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
#include <map>
#include <string>
#include "google/protobuf/compiler/cpp/cpp_field.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
class PrimitiveFieldGenerator : public FieldGenerator {
public:
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~PrimitiveFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
protected:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
};
class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator {
public:
explicit PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~PrimitiveOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator);
};
class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
public:
explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~RepeatedPrimitiveFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
@@ -0,0 +1,642 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include "google/protobuf/compiler/cpp/cpp_string_field.h"
#include "google/protobuf/compiler/cpp/cpp_helpers.h"
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include "google/protobuf/stubs/strutil.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
void SetStringVariables(const FieldDescriptor* descriptor,
map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_length"] =
SimpleItoa(descriptor->default_value_string().length());
(*variables)["default_variable"] = descriptor->default_value_string().empty()
? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()"
: "_default_" + FieldName(descriptor) + "_";
(*variables)["pointer_type"] =
descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char";
// NOTE: Escaped here to unblock proto1->proto2 migration.
// TODO(liujisi): Extend this to apply for other conflicting methods.
(*variables)["release_name"] =
SafeFunctionName(descriptor->containing_type(),
descriptor, "release_");
(*variables)["full_name"] = descriptor->full_name();
}
} // namespace
// ===================================================================
StringFieldGenerator::
StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetStringVariables(descriptor, &variables_, options);
}
StringFieldGenerator::~StringFieldGenerator() {}
void StringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_, "::std::string* $name$_;\n");
}
void StringFieldGenerator::
GenerateStaticMembers(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_, "static ::std::string* $default_variable$;\n");
}
}
void StringFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
// If we're using StringFieldGenerator for a field with a ctype, it's
// because that ctype isn't actually implemented. In particular, this is
// true of ctype=CORD and ctype=STRING_PIECE in the open source release.
// We aren't releasing Cord because it has too many Google-specific
// dependencies and we aren't releasing StringPiece because it's hardly
// useful outside of Google and because it would get confusing to have
// multiple instances of the StringPiece class in different libraries (PCRE
// already includes it for their C++ bindings, which came from Google).
//
// In any case, we make all the accessors private while still actually
// using a string to represent the field internally. This way, we can
// guarantee that if we do ever implement the ctype, it won't break any
// existing users who might be -- for whatever reason -- already using .proto
// files that applied the ctype. The field can still be accessed via the
// reflection interface since the reflection interface is independent of
// the string's underlying representation.
if (descriptor_->options().ctype() != FieldOptions::STRING) {
printer->Outdent();
printer->Print(
" private:\n"
" // Hidden due to unknown ctype option.\n");
printer->Indent();
}
printer->Print(variables_,
"inline const ::std::string& $name$() const$deprecation$;\n"
"inline void set_$name$(const ::std::string& value)$deprecation$;\n"
"inline void set_$name$(const char* value)$deprecation$;\n"
"inline void set_$name$(const $pointer_type$* value, size_t size)"
"$deprecation$;\n"
"inline ::std::string* mutable_$name$()$deprecation$;\n"
"inline ::std::string* $release_name$()$deprecation$;\n"
"inline void set_allocated_$name$(::std::string* $name$)$deprecation$;\n");
if (descriptor_->options().ctype() != FieldOptions::STRING) {
printer->Outdent();
printer->Print(" public:\n");
printer->Indent();
}
}
void StringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return *$name$_;\n"
"}\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" set_has_$name$();\n"
" if ($name$_ == $default_variable$) {\n"
" $name$_ = new ::std::string;\n"
" }\n"
" $name$_->assign(value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" set_has_$name$();\n"
" if ($name$_ == $default_variable$) {\n"
" $name$_ = new ::std::string;\n"
" }\n"
" $name$_->assign(value);\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, size_t size) {\n"
" set_has_$name$();\n"
" if ($name$_ == $default_variable$) {\n"
" $name$_ = new ::std::string;\n"
" }\n"
" $name$_->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" set_has_$name$();\n"
" if ($name$_ == $default_variable$) {\n");
if (descriptor_->default_value_string().empty()) {
printer->Print(variables_,
" $name$_ = new ::std::string;\n");
} else {
printer->Print(variables_,
" $name$_ = new ::std::string(*$default_variable$);\n");
}
printer->Print(variables_,
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" clear_has_$name$();\n"
" if ($name$_ == $default_variable$) {\n"
" return NULL;\n"
" } else {\n"
" ::std::string* temp = $name$_;\n"
" $name$_ = const_cast< ::std::string*>($default_variable$);\n"
" return temp;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$_ != $default_variable$) {\n"
" delete $name$_;\n"
" }\n"
" if ($name$) {\n"
" set_has_$name$();\n"
" $name$_ = $name$;\n"
" } else {\n"
" clear_has_$name$();\n"
" $name$_ = const_cast< ::std::string*>($default_variable$);\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
}
void StringFieldGenerator::
GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
// Initialized in GenerateDefaultInstanceAllocator.
printer->Print(variables_,
"::std::string* $classname$::$default_variable$ = NULL;\n");
}
}
void StringFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
if (descriptor_->default_value_string().empty()) {
printer->Print(variables_,
"if ($name$_ != $default_variable$) {\n"
" $name$_->clear();\n"
"}\n");
} else {
printer->Print(variables_,
"if ($name$_ != $default_variable$) {\n"
" $name$_->assign(*$default_variable$);\n"
"}\n");
}
}
void StringFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "set_$name$(from.$name$());\n");
}
void StringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
}
void StringFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(variables_,
"$name$_ = const_cast< ::std::string*>($default_variable$);\n");
}
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($name$_ != $default_variable$) {\n"
" delete $name$_;\n"
"}\n");
}
void StringFieldGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_,
"$classname$::$default_variable$ =\n"
" new ::std::string($default$, $default_length$);\n");
}
}
void StringFieldGenerator::
GenerateShutdownCode(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_,
"delete $classname$::$default_variable$;\n");
}
}
void StringFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n"
" input, this->mutable_$name$()));\n");
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
"::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$().data(), this->$name$().length(),\n"
" ::google::protobuf::internal::WireFormat::PARSE,\n"
" \"$name$\");\n");
}
}
void StringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
"::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$().data(), this->$name$().length(),\n"
" ::google::protobuf::internal::WireFormat::SERIALIZE,\n"
" \"$name$\");\n");
}
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n"
" $number$, this->$name$(), output);\n");
}
void StringFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
"::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$().data(), this->$name$().length(),\n"
" ::google::protobuf::internal::WireFormat::SERIALIZE,\n"
" \"$name$\");\n");
}
printer->Print(variables_,
"target =\n"
" ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(\n"
" $number$, this->$name$(), target);\n");
}
void StringFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" this->$name$());\n");
}
// ===================================================================
StringOneofFieldGenerator::
StringOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: StringFieldGenerator(descriptor, options) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
StringOneofFieldGenerator::~StringOneofFieldGenerator() {}
void StringOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const ::std::string& $classname$::$name$() const {\n"
" if (has_$name$()) {\n"
" return *$oneof_prefix$$name$_;\n"
" }\n");
if (descriptor_->default_value_string().empty()) {
printer->Print(variables_,
" return ::google::protobuf::internal::GetEmptyStringAlreadyInited();\n");
} else {
printer->Print(variables_,
" return *$default_variable$;\n");
}
printer->Print(variables_,
"}\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = new ::std::string;\n"
" }\n"
" $oneof_prefix$$name$_->assign(value);\n"
"}\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = new ::std::string;\n"
" }\n"
" $oneof_prefix$$name$_->assign(value);\n"
"}\n"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, size_t size) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = new ::std::string;\n"
" }\n"
" $oneof_prefix$$name$_->assign(\n"
" reinterpret_cast<const char*>(value), size);\n"
"}\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n");
if (descriptor_->default_value_string().empty()) {
printer->Print(variables_,
" $oneof_prefix$$name$_ = new ::std::string;\n");
} else {
printer->Print(variables_,
" $oneof_prefix$$name$_ = new ::std::string(*$default_variable$);\n");
}
printer->Print(variables_,
" }\n"
" return $oneof_prefix$$name$_;\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" ::std::string* temp = $oneof_prefix$$name$_;\n"
" $oneof_prefix$$name$_ = NULL;\n"
" return temp;\n"
" } else {\n"
" return NULL;\n"
" }\n"
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" clear_$oneof_name$();\n"
" if ($name$) {\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_ = $name$;\n"
" }\n"
"}\n");
}
void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_,
"delete $oneof_prefix$$name$_;\n");
}
void StringOneofFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
// Don't print any swapping code. Swapping the union will swap this field.
}
void StringOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_,
" $classname$_default_oneof_instance_->$name$_ = "
"$classname$::$default_variable$;\n");
} else {
printer->Print(variables_,
" $classname$_default_oneof_instance_->$name$_ = "
"$default_variable$;\n");
}
}
void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
printer->Print(variables_,
"if (has_$name$()) {\n"
" delete $oneof_prefix$$name$_;\n"
"}\n");
}
// ===================================================================
RepeatedStringFieldGenerator::
RepeatedStringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetStringVariables(descriptor, &variables_, options);
}
RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {}
void RepeatedStringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
printer->Print(variables_,
"::google::protobuf::RepeatedPtrField< ::std::string> $name$_;\n");
}
void RepeatedStringFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
// See comment above about unknown ctypes.
if (descriptor_->options().ctype() != FieldOptions::STRING) {
printer->Outdent();
printer->Print(
" private:\n"
" // Hidden due to unknown ctype option.\n");
printer->Indent();
}
printer->Print(variables_,
"inline const ::std::string& $name$(int index) const$deprecation$;\n"
"inline ::std::string* mutable_$name$(int index)$deprecation$;\n"
"inline void set_$name$(int index, const ::std::string& value)$deprecation$;\n"
"inline void set_$name$(int index, const char* value)$deprecation$;\n"
"inline "
"void set_$name$(int index, const $pointer_type$* value, size_t size)"
"$deprecation$;\n"
"inline ::std::string* add_$name$()$deprecation$;\n"
"inline void add_$name$(const ::std::string& value)$deprecation$;\n"
"inline void add_$name$(const char* value)$deprecation$;\n"
"inline void add_$name$(const $pointer_type$* value, size_t size)"
"$deprecation$;\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() const"
"$deprecation$;\n"
"inline ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_$name$()"
"$deprecation$;\n");
if (descriptor_->options().ctype() != FieldOptions::STRING) {
printer->Outdent();
printer->Print(" public:\n");
printer->Indent();
}
}
void RepeatedStringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const ::std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n"
"inline ::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
"inline void $classname$::set_$name$(int index, const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(value);\n"
"}\n"
"inline void $classname$::set_$name$(int index, const char* value) {\n"
" $name$_.Mutable(index)->assign(value);\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"inline void "
"$classname$::set_$name$"
"(int index, const $pointer_type$* value, size_t size) {\n"
" $name$_.Mutable(index)->assign(\n"
" reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline ::std::string* $classname$::add_$name$() {\n"
" return $name$_.Add();\n"
"}\n"
"inline void $classname$::add_$name$(const ::std::string& value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
"inline void $classname$::add_$name$(const char* value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add_char:$full_name$)\n"
"}\n"
"inline void "
"$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n"
" $name$_.Add()->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_add_pointer:$full_name$)\n"
"}\n");
printer->Print(variables_,
"inline const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"inline ::google::protobuf::RepeatedPtrField< ::std::string>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
"}\n");
}
void RepeatedStringFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Clear();\n");
}
void RepeatedStringFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
}
void RepeatedStringFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
// Not needed for repeated fields.
}
void RepeatedStringFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
"DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n"
" input, this->add_$name$()));\n");
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
"::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$(this->$name$_size() - 1).data(),\n"
" this->$name$(this->$name$_size() - 1).length(),\n"
" ::google::protobuf::internal::WireFormat::PARSE,\n"
" \"$name$\");\n");
}
}
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
"::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$(i).data(), this->$name$(i).length(),\n"
" ::google::protobuf::internal::WireFormat::SERIALIZE,\n"
" \"$name$\");\n");
}
printer->Print(variables_,
" ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
" $number$, this->$name$(i), output);\n"
"}\n");
}
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
printer->Print(variables_,
"for (int i = 0; i < this->$name$_size(); i++) {\n");
if (HasUtf8Verification(descriptor_->file()) &&
descriptor_->type() == FieldDescriptor::TYPE_STRING) {
printer->Print(variables_,
" ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(\n"
" this->$name$(i).data(), this->$name$(i).length(),\n"
" ::google::protobuf::internal::WireFormat::SERIALIZE,\n"
" \"$name$\");\n");
}
printer->Print(variables_,
" target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$ToArray($number$, this->$name$(i), target);\n"
"}\n");
}
void RepeatedStringFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"total_size += $tag_size$ * this->$name$_size();\n"
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" this->$name$(i));\n"
"}\n");
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,127 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
#include <map>
#include <string>
#include "google/protobuf/compiler/cpp/cpp_field.h"
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
class StringFieldGenerator : public FieldGenerator {
public:
explicit StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~StringFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateStaticMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateDestructorCode(io::Printer* printer) const;
void GenerateDefaultInstanceAllocator(io::Printer* printer) const;
void GenerateShutdownCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
protected:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
};
class StringOneofFieldGenerator : public StringFieldGenerator {
public:
explicit StringOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~StringOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateDestructorCode(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator);
};
class RepeatedStringFieldGenerator : public FieldGenerator {
public:
explicit RepeatedStringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
~RepeatedStringFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
@@ -0,0 +1,232 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR 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.
// Author: kenton@google.com (Kenton Varda)
//
// Deals with the fact that hash_map is not defined everywhere.
#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__
#define GOOGLE_PROTOBUF_STUBS_HASH_H__
#include <string.h>
#include <google/protobuf/stubs/common.h>
#include "config.h"
#if defined(HAVE_HASH_MAP) && defined(HAVE_HASH_SET)
#include HASH_MAP_H
#include HASH_SET_H
#else
#define MISSING_HASH
#include <map>
#include <set>
#endif
namespace google {
namespace protobuf {
#ifdef MISSING_HASH
// This system doesn't have hash_map or hash_set. Emulate them using map and
// set.
// Make hash<T> be the same as less<T>. Note that everywhere where custom
// hash functions are defined in the protobuf code, they are also defined such
// that they can be used as "less" functions, which is required by MSVC anyway.
template <typename Key>
struct hash {
// Dummy, just to make derivative hash functions compile.
int operator()(const Key& key) {
GOOGLE_LOG(FATAL) << "Should never be called.";
return 0;
}
inline bool operator()(const Key& a, const Key& b) const {
return a < b;
}
};
// Make sure char* is compared by value.
template <>
struct hash<const char*> {
// Dummy, just to make derivative hash functions compile.
int operator()(const char* key) {
GOOGLE_LOG(FATAL) << "Should never be called.";
return 0;
}
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = int >
class hash_map : public std::map<Key, Data, HashFcn> {
public:
hash_map(int = 0) {}
};
template <typename Key,
typename HashFcn = hash<Key>,
typename EqualKey = int >
class hash_set : public std::set<Key, HashFcn> {
public:
hash_set(int = 0) {}
};
#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION)
template <typename Key>
struct hash : public HASH_NAMESPACE::hash_compare<Key> {
};
// MSVC's hash_compare<const char*> hashes based on the string contents but
// compares based on the string pointer. WTF?
class CstringLess {
public:
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
};
template <>
struct hash<const char*>
: public HASH_NAMESPACE::hash_compare<const char*, CstringLess> {
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = int >
class hash_map : public HASH_NAMESPACE::hash_map<
Key, Data, HashFcn> {
public:
hash_map(int = 0) {}
};
template <typename Key,
typename HashFcn = hash<Key>,
typename EqualKey = int >
class hash_set : public HASH_NAMESPACE::hash_set<
Key, HashFcn> {
public:
hash_set(int = 0) {}
};
#else
template <typename Key>
struct hash : public HASH_NAMESPACE::hash<Key> {
};
template <typename Key>
struct hash<const Key*> {
inline size_t operator()(const Key* key) const {
return reinterpret_cast<size_t>(key);
}
};
// Unlike the old SGI version, the TR1 "hash" does not special-case char*. So,
// we go ahead and provide our own implementation.
template <>
struct hash<const char*> {
inline size_t operator()(const char* str) const {
size_t result = 0;
for (; *str != '\0'; str++) {
result = 5 * result + *str;
}
return result;
}
};
template <typename Key, typename Data,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_map : public HASH_NAMESPACE::HASH_MAP_CLASS<
Key, Data, HashFcn, EqualKey> {
public:
hash_map(int = 0) {}
};
template <typename Key,
typename HashFcn = hash<Key>,
typename EqualKey = std::equal_to<Key> >
class hash_set : public HASH_NAMESPACE::HASH_SET_CLASS<
Key, HashFcn, EqualKey> {
public:
hash_set(int = 0) {}
};
#endif
template <>
struct hash<string> {
inline size_t operator()(const string& key) const {
return hash<const char*>()(key.c_str());
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline size_t operator()(const string& a, const string& b) const {
return a < b;
}
};
template <typename First, typename Second>
struct hash<pair<First, Second> > {
inline size_t operator()(const pair<First, Second>& key) const {
size_t first_hash = hash<First>()(key.first);
size_t second_hash = hash<Second>()(key.second);
// FIXME(kenton): What is the best way to compute this hash? I have
// no idea! This seems a bit better than an XOR.
return first_hash * ((1 << 16) - 1) + second_hash;
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline size_t operator()(const pair<First, Second>& a,
const pair<First, Second>& b) const {
return a < b;
}
};
// Used by GCC/SGI STL only. (Why isn't this provided by the standard
// library? :( )
struct streq {
inline bool operator()(const char* a, const char* b) const {
return strcmp(a, b) == 0;
}
};
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_HASH_H__

Some files were not shown because too many files have changed in this diff Show More