strlen 老瓶装新酒
前言 - strlen 概述
无意间扫到 glibc strlen.c 中代码, 久久不能忘怀. 在一无所知的编程生涯中又记起点点滴滴:
编程可不是儿戏 ❀, 有些难, 也有些不舍. 随轨迹一同重温, 曾经最熟悉的 strlen 手感吧 ~
/* Copyright (C) 1991-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se);
commentary by Jim Blandy (jimb@ai.mit.edu). The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */ #include <string.h>
#include <stdlib.h> #undef strlen #ifndef STRLEN
# define STRLEN strlen
#endif /* Return the length of the null-terminated string STR. Scan for
the null terminator quickly by testing four bytes at a time. */
size_t
STRLEN (const char *str)
{
const char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword, himagic, lomagic; /* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = str; ((unsigned long int) char_ptr
& (sizeof (longword) - )) != ;
++char_ptr)
if (*char_ptr == '\0')
return char_ptr - str; /* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to 8-byte longwords. */ longword_ptr = (unsigned long int *) char_ptr; /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end: bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof (longword) > )
{
/* 64-bit version of the magic. */
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
himagic = ((himagic << ) << ) | himagic;
lomagic = ((lomagic << ) << ) | lomagic;
}
if (sizeof (longword) > )
abort (); /* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
longword = *longword_ptr++; if (((longword - lomagic) & ~longword & himagic) != )
{
/* Which of the bytes was the zero? If none of them were, it was
a misfire; continue the search. */ const char *cp = (const char *) (longword_ptr - ); if (cp[] == )
return cp - str; if (cp[] == )
return cp - str + ;
if (cp[] == )
return cp - str + ;
if (cp[] == )
return cp - str + ;
if (sizeof (longword) > )
{
if (cp[] == )
return cp - str + ;
if (cp[] == )
return cp - str + ;
if (cp[] == )
return cp - str + ;
if (cp[] == )
return cp - str + ;
}
}
}
}
libc_hidden_builtin_def (strlen)
正文 - 思考和分析
1. unsigned long int 字节多大 4 字节, 8 字节 ?
unsigned long int longword, himagic, lomagic;
long 具体多长和平台有关, 例如大多数 linux , x84 sizeof (long) = 4, x64 sizeof (long) = 8.
window x86, x64 sizeof (long) = 4. (2020年05月28日), C 标准保证 sizeof(long) >= sizeof (int)
具体多少字节交给了实现方.
2. ((unsigned long int) char_ptr & (sizeof (longword) - 1)) 位对齐 ?
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = str; ((unsigned long int) char_ptr
& (sizeof (longword) - )) != ;
++char_ptr)
if (*char_ptr == '\0')
return char_ptr - str;
起始的这些代码的作用是, 让 chart_ptr 按照 sizeof (unsigned long) 字节大小进行位对齐.
这涉及到多数计算机硬件对齐有要求和性能方面的考虑等等(性能是主要因素).
3. himagic = 0x80808080L; lomagic = 0x01010101L; what fuck ?
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end: bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof (longword) > )
{
/* 64-bit version of the magic. */
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
himagic = ((himagic << ) << ) | himagic;
lomagic = ((lomagic << ) << ) | lomagic;
}
if (sizeof (longword) > )
abort (); /* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
longword = *longword_ptr++; if (((longword - lomagic) & ~longword & himagic) != )
{
3.1 (((longword - lomagic) & ~longword & himagic) != 0) ? mmp ?
可能这就是艺术吧. 想到这个想法的, 真是个天才啊! 好巧妙. 哈哈哈. 我们会分两个小点说明下.
首次看, 感觉有点萌. 我这里用个简单的思路来带大家理解这个问题. 上面代码主要围绕
sizeof (unsigned long) 4 字节和 8 字节去处理得到. 我们简单点, 通过处理 1 字节, 类比递归机制.
搞懂这个公式背后的原理 (ˇˍˇ) ~
/**
* himagic : 1000 0000
* lomagic : 0000 0001
* longword : XXXX XXXX
* /
unsigned long himagic = 0x80L;
unsigned long lomagic = 0x01L; unsigned long longword ;
随后我们仔细分析下面公式
((longword - lomagic) & ~longword & himagic)
( & himagic ) = ( & 1000 0000) 表明最终只在乎最高位.
longword 分三种情况讨论
longword : 1XXX XXXX =< x <=
longword : 0XXX XXXX < x <
longword : x =
第一种 longword = 1XXX XXXX
那么 ~longword = 0YYY YYYY 显然 ~ longword & himagic = 0000 0000 不用继续了.
第二种 longword = 0XXX XXXX 且不为 0, 及不小于 1
显然 (longword - lomagic) = 0ZZZ ZZZ >= 0 且 < 127, 因为 lomagic = 1;
此刻 (longword - lomagic) & himagic = 0ZZZ ZZZZ & 1000 0000 = 0 , 所以也不需要继续了.
第三种 longword = 0000 0000
那么 ~longword & himagic = 1111 1111 & 1000 0000 = 1000 000;
再看 (longword - lomagic) = (0000 0000 - 0000 0001) , 由于无符号数减法是按照
(补码(0000 0000) + 补码(-000 0001)) = (补码(0000 0000) + 补码(~000 0001 + 1))
= (补码(0000 0000) + 补码(1111 1111)) = 1111 1111 (快捷的可以查公式得到最终结果),
因而 此刻最终结果为 1111 1111 & 1000 0000 = 1000 0000 > 0.
综合讨论, 可以根据上面公式巧妙的筛选出值是否为 0. 对于 2字节, 4 字节, 8 字节, 思路完全相似.
3.2 (sizeof (longword) > 4) ? (sizeof (longword) > 8) 为什么不用宏, 大展宏图呗 ?
宏可以做到多平台源码共享, 无法做到多平台二进制共享. glibc 这么通用项目, 可移植性影响因子
可能会很重. (性能是毒酒, 想活的久还是少喝 ~ )
4. libc_hidden_builtin_def (strlen) ? 闹哪样 ~
理解这个东西, 要引入些场外信息 (不同编译参数会不一样, 这里只抽取其中一条分支解法)
// file : glibc-2.31/include/libc-symbols.h libc_hidden_builtin_def (strlen) #define libc_hidden_builtin_def(name) libc_hidden_def (name) # define libc_hidden_def(name) hidden_def (name) /* Define ALIASNAME as a strong alias for NAME. */
# define strong_alias(name, aliasname) _strong_alias(name, aliasname)
# define _strong_alias(name, aliasname) \
extern __typeof (name) aliasname __attribute__ ((alias (#name))) \
__attribute_copy__ (name); /* For assembly, we need to do the opposite of what we do in C:
in assembly gcc __REDIRECT stuff is not in place, so functions
are defined by its normal name and we need to create the
__GI_* alias to it, in C __REDIRECT causes the function definition
to use __GI_* name and we need to add alias to the real name.
There is no reason to use hidden_weak over hidden_def in assembly,
but we provide it for consistency with the C usage.
hidden_proto doesn't make sense for assembly but the equivalent
is to call via the HIDDEN_JUMPTARGET macro instead of JUMPTARGET. */
# define hidden_def(name) strong_alias (name, __GI_##name) /* Undefine (also defined in libc-symbols.h). */
#undef __attribute_copy__
#if __GNUC_PREREQ (9, 0)
/* Copies attributes from the declaration or type referenced by
the argument. */
# define __attribute_copy__(arg) __attribute__ ((__copy__ (arg)))
#else
# define __attribute_copy__(arg)
#endif
利用上面宏定义, 进行展开
libc_hidden_builtin_def (strlen)
| hidden_def (strlen)
| strong_alias (strlen, __GI_strlen)
| _strong_alias (strlen, __GI_strlen)
| extern __typeof (strlen) __GI_strlen __attribute__ ((alias ("strlen"))) __attribute_copy__ (strlen);
|
extern __typeof (strlen) __GI_strlen __attribute__ ((alias ("strlen"))) __attribute__ ((__copy__ (strlen)));
``
其中 GUN C 扩展语法
后记 - 展望与生活
错误是难免的, 欢迎指正和交流 ~
strlen 老瓶装新酒的更多相关文章
- Service Mesh 是新瓶装旧酒吗?
点击下载<不一样的 双11 技术:阿里巴巴经济体云原生实践> 本文节选自<不一样的 双11 技术:阿里巴巴经济体云原生实践>一书,点击上方图片即可下载! 作者 | 李云(花名: ...
- 老梗新玩「GitHub 热点速览 v.22.34」
作者:HelloGitHub-小鱼干 不知道你是否和我有一样的烦恼,最近的流行梗当自己要用拿来造词时,就陷入了不知道咋"换壳"的尴尬地步.sao-gen-gen 大大减少了你老梗新 ...
- 新瓶装旧酒:全程无命令 GitHub Pages 创建您的博客站点
使用 GitHub Pages 创建博客站点的文章很多,也有很长的历史了.但是,许多已经与当前的 GitHub 不一致了,如果你按图索骥,会发现驴唇对不上马嘴. 更为麻烦的是,你会发现或者需要你输入许 ...
- 老技术新谈,Java应用监控利器JMX(2)
各位坐稳扶好,我们要开车了.不过在开车之前,我们还是例行回顾一下上期分享的要点. 上期由于架不住来自于程序员内心的灵魂的拷问,于是我们潜心修炼,与 Java 应用监控利器 JMX 正式打了个照面. J ...
- IBatis.Net 老技术新研究
我们现在用的数据访问组件封装了IBatis.Net框架,提供了标准的数据访问接口和服务.正好总结一下老技术IBatis.Net在进行实际的数据访问开发之前,我们先了解一下:IBatis.Net中几个重 ...
- 老技术新谈,Java应用监控利器JMX(3)
各位坐稳扶好,我们要开车了.不过在开车之前,我们还是例行回顾一下上期分享的要点. 上期我们深入的聊了聊 JMX,把 JMX 的架构了解了七七八八,最后通过代码实战,解决系列疑问,实现远程动态修改应用参 ...
- 老技术新谈,Java应用监控利器JMX(1)
先聊聊最近比较流行的梗,来一次灵魂八问. 配钥匙师傅: 你配吗? 食堂阿姨: 你要饭吗? 算命先生: 你算什么东西? 快递小哥: 你是什么东西? 上海垃圾分拣阿姨: 你是什么垃圾? 滴滴司机: 你搞清 ...
- Splay POJ3468(老题新做)
A Simple Problem with Integers Time Limit:5000MS Memory Limit:131072KB 64bit IO Format:%I64d ...
- [老法新用]使用PADDING-TOP:(PERCENTAGE)实现响应式背景图片
处理响应式布局中背景图片的简单方法是等比例缩放背景图片.我们知道宽度设为百分比的 <img> 元素,其高度会随着宽度的变化自动调整,且其宽高比不变.如果想在背景图片中实现同样的效果,我们 ...
随机推荐
- MySQL必知必会1-20章读书笔记
MySQL备忘 目录 目录 使用MySQL 检索数据 排序检索数据 过滤数据 数据过滤 用通配符进行过滤 用正则表达式进行搜索 创建计算字段 使用数据处理函数 数值处理函数 汇总数据 分组数据 使用子 ...
- memcached线程模型
直接上图: memcached使用多线程模型,一个master线程,多个worker线程,master和worker通过管道实现通信. 每个worker线程有一个队列,队列元素为CQ_ITEM. ty ...
- 【Hadoop离线基础总结】伪分布模式环境搭建
伪分布模式环境搭建 服务规划 适用于学习测试开发集群模式 步骤 第一步:停止单节点集群,删除/export/servers/hadoop-2.7.5/hadoopDatas,重新创建文件夹 停止单节点 ...
- [hdu5379 Mahjong tree]dfs计数
题意:给n个节点的树编号1-n,一个节点唯一对应一种编号,要求编完号的树满足如下性质:所有节点的儿子的编号是连续的,对一棵子树,它包含的所有节点的编号也是连续的.连续的意思是把所有数排序后是一段连续的 ...
- [hdu5204]水题
思路:插入的数按指数级增长,所以范围内最多存在logR个数.并且最近i次插入的数,首位置为2^(i-1),且每隔2^i出现一次,于是暴力之..可以用插入排序维护,也可查询时再排下序. 一: #prag ...
- Go中操作mysql
Go中操作mysql 首先在mysql里的test数据库中创建数据表 CREATE TABLE `userinfo` ( `uid` INT(10) NOT NULL AUTO_INCREMENT, ...
- 关于日常操作中sql的性能
最近接手了一个项目.使用的数据库是sql server,但是遇到一些关于日期的查询的时候,查询结果非常慢.看了下别人的sql //sql = sql + " and CONVERT(nvar ...
- Javascript中的apply与call
一丶定义 每个函数都包含两个非继承而来的方法:apply()和call().这两个方法的用途都是在特定的作用域中调用函数,实际上等于设置函数体内this对象的值. 1.apply()方法 apply( ...
- 解决 Loaded plugins: fastestmirror
其大概意思是fastestmirror不能使用,fastestmirror是yum的一个加速插件,具体我也没有仔细了解过,可能是系统不支持或者缺少组建导致的.处理办法就是禁用这个插件,方法如下:roo ...
- sh: react-scripts: command not found after running npm start
今天遇到一堆bug,从早上10点到现在8成的时间都像是浪费了..... https://stackoverflow.com/questions/40546231/sh-react-scripts-co ...